iControl REST token authentication via Python example
Problem this snippet solves:
Here's a simple script that shows token authentication working.
How to use this snippet:
Replace the "test" and "api" variables with your username and password. Set the BIG-IP management IP variable in target_bigip.
Code :
#!/usr/bin/env python3
import json,requests
requests.packages.urllib3.disable_warnings()
target_bigip = '10.1.1.134'
def tokenauth(username,password):
apiCall = requests.session()
apiPayload = {}
apiHeaders = {}
apiPayload['username'] = username
apiPayload['password'] = password
apiPayload['loginProviderName'] = 'tmos'
apiHeaders['Content-type'] = 'application/json'
apiUrl = 'https://' + target_bigip + '/mgmt/shared/authn/login'
apiResponse = apiCall.post(apiUrl,data=json.dumps(apiPayload),verify=False,headers=apiHeaders)
apiResponseJson = json.loads(str(apiResponse.text))
return(apiResponseJson['token']['token'])
def restput(token,path,payload):
apiCall = requests.session()
apiCall.auth = None
apiHeaders = {}
apiHeaders['Content-type'] = 'application/json'
apiHeaders['X-F5-Auth-Token'] = token
apiUrl = 'https://' + target_bigip + path
apiResponse = apiCall.put(apiUrl,headers=apiHeaders,data=json.dumps(payload),verify=False)
return(apiResponse.text)
if __name__ == "__main__":
# Perform token authentication
print('Grabbing auth token')
mytoken = tokenauth('rest','api')
print(mytoken)
# Make an API call using the token
print('Making the API call')
mycall = restput(mytoken,'/mgmt/tm/sys/ssh',{"banner-text":"UPDATED!"})
print('API response: ' + mycall)
quit()Tested this on version:
12.0Published Aug 13, 2019
Version 1.0G-Rob
Employee
F5 Solutions Engineer focused on cloud, automation, modern apps and excellent customer-focused service.G-Rob
Employee
F5 Solutions Engineer focused on cloud, automation, modern apps and excellent customer-focused service.No CommentsBe the first to comment