In today’s post I am going to demonstrate how you can take advantage of Aruba AOS-CX’s powerful API. I will demonstrate this by using Python’s Requests library which is designed for sending HTTP requests. Throughout HPe Aruba documentation they provide api examples in Curl, however I prefer to use Python. With that said, here we go.
I will be covering the basics which will allow you to quickly create an API call to an AOS CX switch. For in-depth knowledge on Aruba’s REST API please refer to HPe’s “AOS CX 10.XX REST API Guide”. For in-depth knowledge on Python programing please refer to the many resources available on the Internet.
Things you should know:
AOS-CX supports various versions of the REST API from 10.04 to 10.13 at the time of this post.
The version you use in your API request call must match the version supported on your switch.
In the following example, the REST API version is v10.11: https://192.168.1.10/rest/v10.11/system
AOS-CX API supports read-only and read-write (default) modes
Preparing the Switch:
Before an API call to the CX switch will work you have to setup the device. Please refer to Aruba’s documentation for setup instructions of the switch to support API calls that match your environment. Refer to Aruba’s “ArubaOS-CX 10.XX REST v10.XX API Guide”.
API Call:
For this example API call we will have two files:
device_list.txt = list of IP addresses of devices, one IP per line
aoscx_script.py = python script
Our example python script will use a text file to pull ip addresses of cx switches from. This is so that later on we can have our script run against multiple cx switches. The sample script below imports required python libraries, defines authentication credentials, reads addresses from a file, creates a python function to be used for login, creates a main function, and then makes an api call to cx switch.
device_list.txt file contents
192.168.100.3
192.168.101.103
aoscx_script.py file contents
import requests
import os
USERNAME = "admin"
PASSWORD = "password"
DEVICE_LIST_FILE = "device_list.txt"
creds = {'username': USERNAME, 'password': PASSWORD}
requests.packages.urllib3.disable_warnings()
def login(device_ip, creds):
session = requests.Session()
response = session.post(f"https://{device_ip}/rest/v10.11/login", params=creds, verify=False, timeout=10)
if response.status_code == 200:
print(f"[{device_ip}] ā
Login successful")
return session
else:
raise Exception(f"[{device_ip}] ā Login failed: {response.status_code} - {response.text}")
def main():
if not os.path.exists(DEVICE_LIST_FILE):
print(f"Device list not found: {DEVICE_LIST_FILE}")
return
with open(DEVICE_LIST_FILE) as f:
devices = [line.strip() for line in f if line.strip()]
creds = {"username": USERNAME, "password": PASSWORD}
for device_ip in devices:
print(f"\nš Checking device: {device_ip}")
except Exception as e:
print(f"ā Error on {device_ip}: {e}")
try:
session = login(device_ip, creds)
if __name__ == "__main__":
main()
Anatomy of the API call (detailed explanation with comments in code)
import requests # Imports the 'requests' library, which allows making HTTP/HTTPS requests in Python.
import os # Required for checking file existence
USERNAME = "admin" # Sets the username to be used for logging into the device.
PASSWORD = "password" # Sets the password corresponding to the username.
DEVICE_LIST_FILE = "device_list.txt" # Defines the file name containing the list of device IP addresses.
creds = {'username': USERNAME, 'password': PASSWORD} # Creates a dictionary containing the login credentials.
requests.packages.urllib3.disable_warnings() # Disables SSL certificate verification warnings (often needed when using self-signed certs).
def login(device_ip, creds): # Defines a function named 'login' that accepts a device IP address and credentials dictionary.
session = requests.Session() # Creates a persistent HTTP session object to maintain cookies and settings.
response = session.post(f"https://{device_ip}/rest/v10.11/login", params=creds, verify=False, timeout=10)
# Sends an HTTPS POST request to the device's login endpoint using the provided credentials.
# 'verify=False' bypasses SSL certificate checks, and 'timeout=10' sets the timeout to 10 seconds.
if response.status_code == 200: # Checks if the HTTP response code is 200, indicating a successful login.
print(f"[{device_ip}] ā
Login successful") # Prints a success message including the device IP address.
return session # Returns the session object for further requests to the device.
else:
raise Exception(f"[{device_ip}] ā Login failed: {response.status_code} - {response.text}")
# Raises an exception if login fails, showing the HTTP status code and error message from the response.
def main():
# Check if the device list file exists before proceeding
if not os.path.exists(DEVICE_LIST_FILE):
print(f"Device list not found: {DEVICE_LIST_FILE}")
return # Exit the function if the file does not exist
# Open the file containing device IPs/hostnames and read each line
# Use list comprehension to strip whitespace and ignore empty lines
with open(DEVICE_LIST_FILE) as f:
devices = [line.strip() for line in f if line.strip()]
# Create a credentials dictionary using the username and password from earlier
creds = {"username": USERNAME, "password": PASSWORD}
# Iterate over each device IP address from the list
for device_ip in devices:
print(f"\nš Checking device: {device_ip}") # Indicate which device is being processed
try:
# Attempt to log in to the device using the login function
session = login(device_ip, creds)
# You can continue using 'session' here for further API calls if needed
except Exception as e:
# If an error occurs during login (e.g., network issues or wrong credentials),
# catch the exception and print an error message for that device
print(f"ā Error on {device_ip}: {e}")
# This line ensures the main() function is only executed when the script is run directly,
# and not when it is imported as a module in another script.
if __name__ == "__main__":
main()
Now we have a python script that can be used to make an api call and authenticate to an Aruba cx switch. In my next post I will create a logout function so we can gracefully disconnect from the switch. I hope this post helps. Now go script something.
Leave a comment