Here is an example Python script which uses the API to check the gateway's ports statuses. The almost-completed script is available as an attachment to this page.
Requirements
Python
OpenSSL
Python Modules
sys
re
mechanize
cookielib
urllib
json
pprint
Code
Download the full source code -
Start a new python script.
#!/usr/bin/env python import sys import re import mechanize import cookielib import urllib import json from pprint import pprint
Configure your script with your gateway's IP address and admin password to prepare for the login.
def main(): gateway_ip = 'CHANGEME' gateway_user = 'admin' gateway_pass = 'admin' data = { 'admin_uid': gateway_user, 'admin_password': gateway_pass } data_str = '&'.join(['%s=%s' % (k,v) for k,v in data.iteritems()])
Create mechanize and cookielib objects using this information and tell the mechanize object about your cookie jar. Submit the login request and test for a successful result.
# Log in req = mechanize.Request("https://%s/admin/main.html" % gateway_ip, data_str) cj = cookielib.LWPCookieJar() cj.add_cookie_header(req) res = mechanize.urlopen(req) lines = res.read() # Response from login is an HTML page. Check that the main page's init() # function is called to be sure we have logged in and are looking at # the main page. if re.search("Welcome,\s+%s" % gateway_user, lines) is None: print "Login Failed!" return 1
Build a call to the connection_status.list method and submit it. On my system, I had to tell
json
not to put spaces in our string separators, because these spaces were being turned into null characters somewhere down the line, which the Perl json decoder the gateway uses cannot parse.# Request connection status data = { "request" : { "method": "connection_status.list", } } # Something (mechanize?) doesn't like JSON with spaces in it. data_str = json.dumps(data, separators=(',',':')) req = mechanize.Request("https://%s/json" % gateway_ip, data_str) res = mechanize.urlopen(req)
Read the result.
# read lines = res.read() response = json.loads(lines) result = json.loads(response['response']['result']) # check result for interface in result['connection_status']['t1_e1_interfaces']: if interface['status_desc'] != 'Up, Active': print "%s is down (status '%s') on %s!" % ( interface['name'], interface['status_desc'], gateway_ip ) # Send an email, postcard, or pidgeon to the sysadmin
Call main().
sys.exit(main() or 0)