Getting the list of Guests present in the system

This code, connects to Manager, authenticates and gets a list of all Guests present in that installation.

Implements the following arguments:

  • -m: Manager's address (required)
  • -p: Manager's password (optional, if not present, password will be asked)

 

#!/usr/bin/env python
 
import ssl
# Recent Python versions require a valid certificate. You can comment this
# if you've loaded a valid certificate in your Manager instance
if hasattr(ssl, '_create_unverified_context'):
    ssl._create_default_https_context = ssl._create_unverified_context
 
import sys
import getpass
import json
from optparse import OptionParser
from optparse import OptionGroup
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
from cookielib import CookieJar
 
if __name__ == "__main__":
    parser = OptionParser(conflict_handler="resolve")
    parser.add_option("-m", "--manager", dest="manager",
            help="connect to this Manager ", metavar="MANAGER")
    parser.add_option("-p", "--password", dest="password", 
            help="admin password", metavar="PASSWORD")
 
    if len(sys.argv) < 2:
        parser.print_help()
        sys.exit(-1)
 
    (options, args) = parser.parse_args(sys.argv[1:])
 
    if options.manager is None:
        parser.print_help()
        sys.exit(-1)
 
    if options.password is None:
        options.password = getpass.getpass('Enter admin password: ')
 
    # We need to use CookieJar to store the session ID injected by Manager
    cj = CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
 
    # Prepare an Authenticate Object
    authenticate = {"username": "admin", "password": options.password}
 
    # Prepare urllib2 request, converting auth_object to JSON in the process
    authurl = 'https://' + options.manager + '/authenticate'
    request = urllib2.Request(authurl, json.dumps(authenticate))
    request.add_header('Content-type', 'application/json')
    response = opener.open(request)
    rawdata = response.read()
 
    # Try to parse response as an AuthResult Object
    try:
        authresult = json.loads(rawdata)
    except Exception as ex:
        print 'Can\'t parse Manager response as AuthResult Object'
        print 'Data: ' + rawdata
        print
        sys.exit(-1)
    if 'status' in authresult:
        if authresult['status'] != 'OK':
            print 'Manager reject this credentials'
            print
            sys.exit(-1)
    else:
        print 'Invalid answer from Manager'
        print 'JSON Data: ' + authresult
        print
        sys.exit(-1)
 
    # At this point, we have a valid session cookie in out CookieJar.
    # Reuse to get the list of all Guests
    guestsurl = 'https://' + options.manager + '/guests'
    request = urllib2.Request(guestsurl)
    response = opener.open(request)
    rawdata = response.read()
 
    # Try to parse answer as an array of GuestBasicInfo, and dump its contents
    try:
        guestinfo = json.loads(rawdata)
        for guest in guestinfo:
            print '=========================================='
            print 'Basic Info for Guest: ' + guest['guest_id']
            print guest
    except Exception as ex:
        print 'Can\'t parse Manager answer a an array of GuestBasicInfo'
        print 'Data: ' + rawdata
        print
        sys.exit(-1)