Example Python Script - Send Email on Red Alarm
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.
- 1 Requirements
- 2 Code
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.Read the result.
Call main().
Â