Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Start a new python script.

    Code Block
    #!/usr/bin/env python
     
    import sys
    import re
    import mechanize
    import cookielib
    import urllib
    import json
    from pprint import pprint
  2. Configure your script with your gateway's IP address and admin password to prepare for the login.

    Code Block
    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()])
  3. 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.

    Code Block
    # 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
  4. 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.

    Code Block
    # 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)
  5. Read the result.

    Code Block
    # 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
  6. Call main().

    Code Block
    sys.exit(main() or 0)

...