Advertisement
vnick

guacamole.py

Dec 31st, 2017
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.42 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import json
  4. import urllib
  5. import urllib2
  6. import sys
  7. import pandas
  8. import argparse
  9.  
  10. guacbase = "https://server.example.com/guacamole"
  11.  
  12. # Parse arguments
  13. def parse_args(args=None):
  14.     parser = argparse.ArgumentParser(description='Guacamole Command Line Utility.')
  15.     parser.add_argument('-a', dest='active', action='store_true', help='Show active connections')
  16.     parser.add_argument('-l', dest='history', action='store_true', help='List session history')
  17.     parser.add_argument('-k', '--kill', dest='kill', type=str, metavar='UUID', help='Kill the session with the specified UUID.')
  18.  
  19.     return parser.parse_args()
  20.  
  21. # Login to Guacamole with username/password
  22. def login(username, password):
  23.     loginData = urllib.urlencode({ u'username' : username, u'password' : password })
  24.     loginHeaders = { 'Content-type' : 'application/x-www-form-urlencoded', 'Accept' : 'application/json' }
  25.     loginRequest = urllib2.Request(guacbase + '/api/tokens', data=loginData, headers=loginHeaders)
  26.     loginResponse = urllib2.urlopen(loginRequest)
  27.  
  28.     if loginResponse.code > 299:
  29.         return -1
  30.  
  31.     else:
  32.         return json.loads(loginResponse.read())
  33.  
  34. # Logout of Guacamole with token
  35. def logout(token):
  36.     logoutOpener = urllib2.build_opener(urllib2.HTTPHandler)
  37.     logoutRequest = urllib2.Request(guacbase + '/api/tokens/' + token)
  38.     logoutRequest.get_method = lambda: 'DELETE'
  39.    
  40.     return logoutOpener.open(logoutRequest)
  41.  
  42. # Retrieve the list of active connections
  43. def getActiveConnections(token, dataSources):
  44.     activeConnections = {}
  45.     for datasource in dataSources:
  46.         activeRequest = urllib2.Request(guacbase + '/api/session/data/' + datasource + '/activeConnections?token=' + token)
  47.         activeResponse = urllib2.urlopen(activeRequest)
  48.         if activeResponse.code > 299:
  49.             break
  50.         activeConnections[datasource] = json.loads(activeResponse.read())
  51.  
  52.     return activeConnections
  53.  
  54. # Retrieve the list of historical connections
  55. def getConnectionHistory(token, dataSources):
  56.     connectionHistory = {}
  57.     for datasource in dataSources:
  58.         historyRequest = urllib2.Request(guacbase + '/api/session/data/' + datasource + '/history/connections?token=' + token)
  59.         historyResponse = urllib2.urlopen(historyRequest)
  60.         if historyResponse.code > 299:
  61.             break
  62.         connectionHistory[datasource] = json.loads(historyResponse.read())
  63.  
  64.     return connectionHistory
  65.  
  66. # Look for and kill the session specified by identifier
  67. def killActiveSession(token, dataSources, identifier):
  68.     activeConnections = getActiveConnections(token, dataSources)
  69.     for datasource in dataSources:
  70.         if identifier in activeConnections[datasource]:
  71.             killBody = json.dumps([{ 'op' : 'remove', 'path' : '/' + identifier }])
  72.             killHeaders = { 'Content-type' : 'application/json', 'Accept' : 'application/json' }
  73.             killOpener = urllib2.build_opener(urllib2.HTTPHandler)
  74.             killRequest = urllib2.Request(guacbase + '/api/session/data/' + datasource + '/activeConnections?token=' + token, data=killBody, headers=killHeaders)
  75.             killRequest.get_method = lambda: 'PATCH'
  76.  
  77.             return killOpener.open(killRequest)
  78.     print "No connection found with identifier " + identifier
  79.  
  80. # Login
  81. myLoginData = login('guacuser','guacpassword')
  82.  
  83. # If login failed, exit with failure code
  84. if isinstance(myLoginData, (int,long)):
  85.     sys.exit(myLoginData)
  86.  
  87. # Parse arguments
  88. myArgs = parse_args(sys.argv[1:])
  89.  
  90. TOKEN = myLoginData['authToken']
  91. DATASOURCES = myLoginData['availableDataSources']
  92.  
  93. # If asked for active connections, get them and print them
  94. if myArgs.active:
  95.     ACTIVE = getActiveConnections(TOKEN, DATASOURCES)
  96.     for datasource in DATASOURCES:
  97.         if len(ACTIVE[datasource]) > 0:
  98.             print ACTIVE[datasource].items()
  99.  
  100. # If asked for history, get historical connections and print them
  101. if myArgs.history:
  102.     HISTORY = getConnectionHistory(TOKEN, DATASOURCES)
  103.     for datasource in DATASOURCES:
  104.         if len(HISTORY[datasource]) > 0:
  105.             pandas.set_option('display.width', 1000)
  106.             print pandas.DataFrame(HISTORY[datasource], columns=['username','startDate','endDate','remoteHost','connectionName','active'])
  107.  
  108. # If asked to kill a session, pass info over to kill it
  109. if myArgs.kill:
  110.     killActiveSession(TOKEN, DATASOURCES, myArgs.kill)
  111.  
  112. # Log out when done
  113. logout(TOKEN)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement