Developer

last person joined: 2 days ago 

MM API login techniques with Python and 'show version'

This thread has been viewed 16 times
  • 1.  MM API login techniques with Python and 'show version'

    Posted Dec 08, 2020 04:20 PM
    Posting for future reference. Here are some login techniques I've tested and wanted to post for others to use if they are brand new to the API using Python. Hopefully these techniques save you some time.
    You'll have to forgive me that this isn't PEP8 compliant; I'm still new to python and wrote the majority of this code before I even learned what PEPs were.
    import requests
    import arubaapi
    import json
    
    
    myUsername = 'dummyUsername'
    myPassword = 'dummyPassword'
    aosDeviceFqdn = 'dummy-mm.example.com'
    
    
    def aosLogin():
        """Logs into the AOS device, returns <class requests.Session()> object and UID string"""
    
        session = requests.Session()
    
        myUrl = f'https://{aosDeviceFqdn}:4343/v1/api/login'
        credentials = {
            'username': myUsername ,
            'password': myPassword
        }
        
        try:
            loginResponse = session.get( url=myUrl, params=credentials )
            #loginResponse = session.post( url=myUrl, data=credentials ) # same result
        
        except requests.exceptions.ConnectionError: 
            print(f"Failed to reach {aosDeviceFqdn}, check that you are connected to VPN and that {aosDeviceFqdn} resolves properly in DNS")
            exit()
        
        except KeyError:
            print ("Please check the username and password, and that your account has permission to log in and is not locked.")
            exit()
    
        jsonLoginResponse = loginResponse.json()
    
        arubaUid1 = jsonLoginResponse['_global_result']['UIDARUBA'] # this method of retrieving the UID is only available in the response of the login action
        arubaUid2 = getUidFromSession(session) # this is the same result as arubaUid1, extracted a different way, available anytime an open, logged-in session exists
    
        return arubaUid1 , session
    
    
    def getUidFromSession( session ):
        """Takes a logged in <class requests.Session()> object and returns the UID"""
        myUid = ''
        for thisCookie in session.cookies:
            if (thisCookie.name == "SESSION" and thisCookie.domain == aosDeviceFqdn):
                myUid = thisCookie.value
                break
        return myUid
    
    
    # A different way to log in using the showcommand API wrapper library 'arubaapi'
    def runCommandsWithArubaApiClass ( showCommand ):
        """
        This is a wrapper function for the arubaapi library which handles exceptions for
        'access denied' and unformatted responses
        
        The arubaapi library is itself a wrapper for the showcommand API
        
        The arubaAPI() object has a requests.Session() object embedded as the property
        'session', which you can reuse if you want to have the same session object in future
        calls
    
        Commands rules:
        * Commands must be typed in full, no shorthand (e.g. 'sh ap datab' will not work,
        but 'show ap database' does work
        * You can't use '| include' or any similarly piped parameters
        * Known BAD commands (won't work at all): 'show running-config'
        * Known unformatted commands: 'show version'
    
        Params: string of a show command
        Returns: arubaAPI object , uid string , dict response from running the show commands
        """
    
        showCommand = 'show version' # only an example; can be anything except a BAD command
        
        try:
            myApiSession = arubaapi.ArubaAPI( aosDeviceFqdn , myUsername, myPassword) # this doesn't log you in
    
            # myApiSession logs in and runs the show command
            showCommandOutputDict = myApiSession.cli( showCommand ) # showCommandOutputDict: an outer dict with the full response from arubacli
        
        except requests.exceptions.ConnectionError: 
            print(f"Failed to reach {aosDeviceFqdn}, check that you are connected to VPN")
            exit()
    
        except KeyError:
            print ("Access Denied; check username and password, make sure account is unlocked and has permission to log in.")
            exit()
    
        # a ValueError exception occurs when the response is an unstructured string, such as 'show version'
        except ValueError as valueErrorExceptionTuple:
            argList = []
            if len(valueErrorExceptionTuple.args) == 1:
                thisArg = valueErrorExceptionTuple.args[0].replace('\\r\\n' , '\\n')
                thisArg = thisArg.replace('\\n' , '\n')
                thisArg = thisArg.replace('\\t' , '\t')
                argList = thisArg.splitlines() # argList is a list of strings
    
            # I'm not sure if this else block will ever be used
            else:
                for thisArg in valueErrorExceptionTuple.args: #.args is a tuple
                    thisArg = thisArg.replace('\\r\\n' , '\\n')
                    thisArg = thisArg.replace('\\n' , '\n')
                    thisArg = thisArg.replace('\\t' , '\t')
                    thisArg = thisArg.splitlines()
                    argList.append(thisArg) # argList is a list of lists of strings
            
            unstructuredShowCommandOutputDict = {'ValueError data':argList}
    
            # here's what you can do with show version:
            #parseShowVersion(unstructuredShowCommandOutputDict)
    
            uid = getUidFromSession (myApiSession.session) #now you can use uid to make your own API calls without the arubaapi library
            
            # if you want to reuse the same session, just call the propery myApiSession.session
            return myApiSession , uid , unstructuredShowCommandOutputDict
    
        # this return command sits outside the try/except block
        return myApiSession , uid , showCommandOutputDict
    
    
    def parseShowVersion(showVersionOutputDict):
        """parses runCommandsWithArubaApiClass ( 'show version' )"""
        for string in exampleShowCommandOutputDict['ValueError data']:
            if string.find('ArubaOS') > -1 and string.find('Version') > -1:
                print (string)
                break
        return "Platform and Version: " + string)
    


    ------------------------------
    Tim Haynie, CWNE 254, ACMX 508, ACDX 384
    ------------------------------