Developer

 View Only
last person joined: 2 days ago 

Expand all | Collapse all

Help with a working python script for Aruba CX APi calls

This thread has been viewed 56 times
  • 1.  Help with a working python script for Aruba CX APi calls

    Posted May 05, 2023 12:00 PM

    Hi need some help, 

    please can somebody help me with a working example of logging into a CX switch using APi Calls,

    I'd be happy just to do a show version at the moment.

    I feel like I've watched every video on you tube, i've read the documentation, purchased all the books without making much progress.

    I have Python 3 installed, with PyCham, 
    I cant use Paramiko or Netmiko on CX 
    I have tried using pyaoscx but have no idea how to use it and cant find a working example. 

    I'd really like to do it with APi calls, but cant get any response. 

    This is what I have got 

    import requests
    from getpass4 import getpass

    username = input("Enter Username: ")
    password = getpass('Password: ')
    baseurl = "https://192.168.4.199/rest/v10.11/"

    creds = {"username": username, "password": password}


    s = requests.Session()

    login = s.post(baseurl + "login?", params=creds, verify=False, timeout=2)
    print("Login Status: ", login.status_code, "Cookie: ", login.cookies)

    logout = s.post(baseurl + "logout", verify=False, timeout=2)
    print("Login Status: ", login.status_code, "Cookie: ", login.cookies)



    This was from - Login with Python - Python and ArubaOS-CX 2

    YouTube remove preview
    Login with Python - Python and ArubaOS-CX 2
    Use Python to login to the REST API of new ArubaOS-CX switches. Here's a step-by-step 'how to' demo. Twitter..........►https://twitter.com/joeneville_
    View this on YouTube >


    with a few updates to my script.




  • 2.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 05, 2023 01:08 PM

    Hi Andrew! I'm sorry to hear you're having difficulties - can you share what error you get with the above code? I'm sorry you're having difficulty with the PYAOSCX package, I recommend using our instance on the Python readthedocs for finding modules and their required parameters. Here is an example workflow that configures VLANs and shows how to use our object oriented package on creating a session object.

    For your "show version" desired output here would be the following code:

    from pyaoscx.session import Session
    from pyaoscx.device import Device
    from getpass4 import getpass
    import urllib3
    
    urllib3.disable_warnings()
    
    username = input("Enter Username: ")
    password = getpass('Password: ')
    version = "10.09"
    switch_ip = "10.6.7.16"
    s = Session(switch_ip, version)
    s.open(username, password)
    
    try:
        device = Device(s)
        version = device.get_firmware_version()
        print(version)
    
    
    except Exception as error:
        print("Ran into exception: {0}. Closing session.".format(error))
    
    finally:
            s.close()
    



    ------------------------------
    Ti Chiapuzio-Wong (they/them)
    HPE Aruba Networking
    ------------------------------



  • 3.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 08, 2023 10:42 AM

    Thanks Ti

    Unfortunately I get nothing with running the script... I have to stop the script from executing with no error message when I use the code above.  
    I have updated the switch version 10.11 as that is what I am using, 
    I checked https-server is enable,
    I have logged into the GUi and checked the username and password in the swagger interface and got a success, 

    When i look at the switch logs, there is no evidence of the script trying to access the switch. 

    I'd be happy to be able to within python to just do a 

    post https://192.168.4.199/rest/v10.11/login?username=admin&password=Aruba123

    and get a login status code back at this point. 




  • 4.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 08, 2023 12:32 PM

    at this point v10.11 isn't supported in pyaoscx but 10.09 is still supported with firmware version 10.11 - do you have a proxy set in your environment? when you say you're executing the script and you have to stop it- is it just executing with no output? did you copy/paste the code I sent?

    what version of python are you using? are you using a python virtual env?



    ------------------------------
    Ti Chiapuzio-Wong (they/them)
    HPE Aruba Networking
    ------------------------------



  • 5.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 09, 2023 05:55 AM

    Thanks for helping, I do appreciate it.
    I am using pycham, with Python 3.11, 
    I have installed pyoscx into the project.
    I copied the code (and left the version as 10.09)
    I don't have a proxy in my setup. I have a direct connection to switch.
    When I try with a simple get command I get a certificate error, so i believe connectivity is fine. 

    I ran in debug mode and I keep getting the prompt when pressing enter. I enter the username and password but nothing after that.





  • 6.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 09, 2023 06:00 AM

    Also, am very new to python, still getting to gripes with the basic set ups, I do appreciate the support.





  • 7.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 09, 2023 01:29 PM

    Can you share the error you receive when you copy/paste the code I provided? No debug mode or anything



    ------------------------------
    Ti Chiapuzio-Wong (they/them)
    HPE Aruba Networking
    ------------------------------



  • 8.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 10, 2023 05:01 AM

    I made a video of what is happening, 
    I also added an extra step to show I have connection to the switch over HTTPS

    https://youtu.be/7d-5ubOhgRw





  • 9.  RE: Help with a working python script for Aruba CX APi calls

    MVP GURU
    Posted May 15, 2023 08:37 AM

    Do you have check the Log switch ? (and also make a packet capture to see what is happening ?)



    ------------------------------
    PowerArubaSW : Powershell Module to use Aruba Switch API for Vlan, VlanPorts, LACP, LLDP...

    PowerArubaCP: Powershell Module to use ClearPass API (create NAD, Guest...)

    PowerArubaCL: Powershell Module to use Aruba Central

    PowerArubaCX: Powershell Module to use ArubaCX API (get interface/vlan/ports info)..

    ACEP / ACMX #107 / ACDX #1281
    ------------------------------



  • 10.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 05, 2023 06:29 PM

    Tiffany's PYAOSCX looks like the way to go.  But, if you're interested, I got netmiko to work for me.

    #!/usr/bin/env python3
    '''This module will house the function which can be called
    to build a netmiko handler, and return it.
    
    Brannen Taylor
    9/8/22'''
    
    #STEP 5
    # Moving build_netmiko into main script of gg_lt_aruba_netmiko_mac_lookup_v2 - Brannen 9/19
    def build_netmiko (os:str=None, ip:str=None, user:str=None, password:str=None):
        '''Builds a netmiko connector, called "net_connect" and returns it.
        Does not validate IP address.  Does not retrieve credentials.'''
       
        import logging
        from netmiko import ConnectHandler
        
        #Build a dictionary to pass into netmiko connection handler.
        if os == 'cisco_ios':
            device = {
                'device_type':os,
                'host':ip,
                'username':user,
                'password':password,
                'port':22
            }
        elif os == 'ARUBA' or os == 'aruba_osswitch':
            device = {
                'device_type':'arba_ossuwitch',
                'host':ip,
                'username':user,
                'password':password,
                'port':22
            }
        else:
            logging.warning(f"OS not found. net_dict not built")
            device = None
        
        #STEP 4
        #Establish an SSH connection to the device by passing in the device dictionary.
        net_connect = ConnectHandler(**device)
    
        return net_connect
    
    def main():
        '''Main Function'''
        pass
        
    # Main
    
    if __name__ == '__main__':
        main()


    Truncated code to log into a CX switch:

    """Author: Brannen Taylor - 9/21/22.'''
    
    import logging
    import macaddress # requires pip install macaddress.
    import json
    import os
    import re
    
    from dotenv import load_dotenv
    from netmiko import ConnectHandler
    
    #######################################################################
    
    #STEP 5
    def build_netmiko (os:str=None, ip:str=None, user:str=None, password:str=None):
        '''Builds a netmiko connector, called "net_connect" and returns it.
        Does not validate IP address.  Does not retrieve credentials
    
        see: http://ktbyers.github.io/netmiko/PLATFORMS.html
        
        Parameters:\n
        os - string - a netmiko string description of the os of the network device.\n
        ip - string - an IPv4 address of the network device\n
        user - string - a string for the username to log into the network device.\n
        password - string - the password to log into the network device.
        
        Return:\n
        Returns a netmiko "connect handler" object.'''
    
        # brought in function from 'fa_build_netmiko_connecthandler.py'
    
        # Build a dictionary, to pass to the connect handler via **device argument (= **kwargs)
        if os == 'ARUBA' or os == 'aruba_osswitch':
            device = {
                'device_type':'aruba_osswitch', # aruba_osswitch is a Supported SSH device_type values
                'host':ip,
                'username':user,
                'password':password,
                'port':22,
                }
        else:
            logging.warning(f"OS not found. net_dict not built")
            device = None
        
        #STEP 4
        #Establish an SSH connection to the device by passing in the device dictionary.
        try:
            net_connect = ConnectHandler(**device)
        except Exception as e:
            logger.error("LOGGER-ERROR Tried to load netmiko ConnectHandler at line ~93 and failed.\n{e}")
            net_connect = None
    
        return net_connect
    
    #STEP 6,12
    def send_to_network(net_connect, network_command):
        '''Send a a command via netmiko net_connect to a network device.
        Return the device output
        
        Parameters:\n
        net_connect - netmiko.connecthandler object - an established netmiko connection\n
        network_command - str - the command to issue to the network device.
        
        Return:\n
        device_output - str - a string of the network device's output as a result of the network_command.'''
        device_output = net_connect.send_command(network_command)
        LOCAL and logger.debug(f"LOGGER-DEBUG Device output: {network_command} {device_output}")
        return device_output


    ------------------------------
    Brannen Taylor
    LendingTree
    Manager, Network Operations
    ------------------------------



  • 11.  RE: Help with a working python script for Aruba CX APi calls

    Posted May 08, 2023 10:44 AM

    Thanks Brannen, looks like you have made some good progress there. Am not quite at that stage yet, early days for me at the moment. 

    When I am a little more fluent then lets trade scripts and ideas,