Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 183 lines (144 sloc) 5.92 KB
# !/usr/bin/python3
# This Python script shows how to make basic REST API calls to an NSX
# Manager Server.
# More information on the NSX Manager REST API is here:
# Import Requests library
import requests
import base64
import ssl
import urllib.request
import time
from datetime import datetime
import sys
authorizationField = ''
#Function definition, validate credentials of NSX manager
def nsxSetup(username, password):
'''Setups up Python's urllib library to communicate with the
NSX Manager. Uses TLS 1.2 and no cert, for demo purposes.
Sets the authorization field you need to put in the
request header into the global variable: authorizationField.
global authorizationField
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_NONE
httpsHandler = urllib.request.HTTPSHandler(context=context)
manager = urllib.request.HTTPPasswordMgrWithDefaultRealm()
authHandler = urllib.request.HTTPBasicAuthHandler(manager)
# The opener will be used for for all urllib calls, from now on.
opener = urllib.request.build_opener(httpsHandler, authHandler)
basicAuthString = '%s:%s' % (username, password)
field = base64.b64encode(basicAuthString.encode('ascii'))
# Debugging: print('Basic %s' % str(field,'utf-8'))
authorizationField = 'Basic %s' % str(field, 'utf-8')
#Function definition, get information from NSX manager in xml format
def nsxGet(url, fileName=None):
'''Does a HTTP GET on the NSX Manager REST Server.
If a second argument is given, the result is stored in a file
with that name. Otherwise, it is written to standard output.
global authorizationField
request = urllib.request.Request(url,
headers={'Authorization': authorizationField})
response = urllib.request.urlopen(request)
if fileName == None:
print('REST %s:' % url)
print('REST %s is in file %s.' % (url, fileName))
with open(fileName, 'w') as newFile:
print(, file=newFile)
nsxmanager = ''
nsxuser = 'admin'
nsxpass = 'VMware1!'
api_call_1 = '/api/4.0/edges/edge-3/ipsec/config'
api_call_2 = '/api/4.0/edges/edge-3/ipsec/statistics'
nsxheaders = {'Content-Type': 'application/xml'}
api_response_file_1 = 'edge-3_IPsec_Config.xml'
api_response_file_2 = 'edge-3_IPsec_Statistics.xml'
api_response_file_3 = 'edge-3_IPsec_Config2.xml'
edgeConfigModification = ''
#Test for connectivity to the NSX Manager. If error with connection, exit program gracefully
response = requests.get(nsxmanager + api_call_1, auth=(nsxuser, nsxpass), verify=False, headers=nsxheaders)
except requests.exceptions.Timeout as e:
# Maybe set up for a retry, or continue in a retry loop
print("\nConnection timeout\n" + e)
except requests.exceptions.TooManyRedirects as e:
# Tell the user their URL was bad and try a different one
print("\nToo many redirects\n" + e)
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
#NSX Manager login credentials
#NSX Manager's REST API call
nsxGet(nsxmanager + api_call_1, api_response_file_1)
#NSX Manager's REST API call
nsxGet(nsxmanager + api_call_2, api_response_file_2)
#Read in the REST API call information from the file and put into variable edgeConfig
file1 = open(api_response_file_1, 'r')
edgeConfig =
#Read in the REST API call information from the file and put into variable edgeStatistics
file2 = open(api_response_file_2, 'r')
edgeStatistics =
#print the results of the API call to the terminal window
#Check if the tunnel status is down, if its down and the tunnel is still enabled, turn the tunnel off
if (edgeStatistics.find('<siteId>ipsecsite-3</siteId><ikeStatus><channelStatus>down</channelStatus>') > -1):
nsxpayload = edgeConfigModification
# REST API call using requests.get function from request
#library. Set verify to False to ignore SSL
response = requests.put(nsxmanager + api_call_1,
data = nsxpayload,
auth = (nsxuser, nsxpass),
verify = False,
headers = nsxheaders)
# Print HTTP Response Code
print (response)
# Print XML Content
print (response.text)
#pause the program for 5 seconds so we don't overwhelm the NSX Manager with REST api calls
#Get information about NSX Edge IPsec tunnels again so we can turn on the tunnels back on
nsxGet(nsxmanager + api_call_1, api_response_file_3)
#Read in the REST API call response information again
file3 = open(api_response_file_3, 'r')
edgeConfig2 =
#If the tunnel is disabled, make the proper command to re-enable it
edgeConfigModification2 = edgeConfig.replace('<sites><site><enabled>false</enabled><name>','<sites><site><enabled>true</enabled><name>')
#prepare the tunnel enable command to be sent over the REST api
nsxpayload2 = edgeConfigModification2
# Send the REST api command to re-enable the tunnel
response2 = requests.put(nsxmanager + api_call_1,
data = nsxpayload2,
auth = (nsxuser, nsxpass),
verify = False,
headers = nsxheaders)
# Print HTTP Response Code
print (response2)
# Print XML Content
print (response2.text)
#document what time the script re-opened the tunnel
now =
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
file4 = open('IPsec_Script_Log.txt', 'a+')
file4.write('Tunnel failed and re-initialized at: ' + dt_string + '\n')
print("\nThe tunnel is up, no action taken.\n")
You can’t perform that action at this time.