Of course! The term "Python OpenSwitch" can refer to a few different things, but the most common and important one is using Python to automate and interact with ArubaOS-Switch (formerly HP ProCurve and HPE FlexFabric), which is the operating system for Aruba network switches.

Let's break down the different ways you can use Python with ArubaOS-Switch.
The Primary Method: Using Aruba's REST APIs (Recommended)
Modern ArubaOS-Switch versions (like 10.07 and later) have a robust and well-documented REST API. This is the most powerful, modern, and recommended way to automate your switches with Python.
How it Works:
You send HTTP requests (GET, POST, PUT, DELETE) from your Python script to specific endpoints on the switch. The switch responds with data, usually in JSON format, which Python can easily parse.
Key Benefits:
- Structured Data: JSON is easy to work with in Python.
- Stateless: REST is stateless, making it scalable and reliable.
- Comprehensive: You can perform almost any configuration task via the API, including viewing interfaces, VLANs, ARP tables, LLDP neighbors, and more.
- Web-Friendly: It's the standard for modern web-based automation.
Example: Getting the Interface Status
Let's write a Python script to fetch the operational status of all interfaces on an Aruba switch.

Prerequisites:
- An ArubaOS-Switch with REST API enabled.
- A user with API access (and its password).
- Python installed with the
requestslibrary (pip install requests).
Python Script (get_interfaces.py):
import requests
import json
# --- Configuration ---
SWITCH_IP = "192.168.1.254"
USERNAME = "api_user"
PASSWORD = "your_secure_password"
API_BASE_URL = f"https://{SWITCH_IP}/rest/v10.07"
# --- Disable SSL Warning for self-signed certs (use in dev only) ---
# In production, you should use a valid SSL certificate.
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
# --- Main Logic ---
try:
# 1. Get an authentication token
# The 'Content-Type' header is important for the login request.
auth_url = f"{API_BASE_URL}/login"
headers = {'Content-Type': 'application/json'}
payload = {"user": USERNAME, "password": PASSWORD}
response = requests.post(auth_url, headers=headers, data=json.dumps(payload), verify=False)
response.raise_for_status() # Raises an exception for bad status codes (4xx or 5xx)
# Extract the session token from the response
session_token = response.json()['session_token']
print("Successfully logged in and received token.")
# 2. Use the token to get interface data
# The 'session_token' is passed in the 'Cookie' header for subsequent requests.
interfaces_url = f"{API_BASE_URL}/system/interfaces"
headers = {'Cookie': f session_token={session_token}}
response = requests.get(interfaces_url, headers=headers, verify=False)
response.raise_for_status()
# 3. Process the JSON response
interfaces_data = response.json()
print("\n--- Interface Status ---")
for interface in interfaces_data['interfaces']:
name = interface['name']
oper_status = interface['oper_status']
print(f"Interface: {name:<15} Status: {oper_status}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
To Run the Script:
python get_interfaces.py
Output:
Successfully logged in and received token.
--- Interface Status ---
Interface: 1/1/1 Status: up
Interface: 1/1/2 Status: down
Interface: 1/1/3 Status: up
Interface: 1/1/4 Status: up
The Classic Method: Using Paramiko (SSH)
If your switch is running an older version of ArubaOS-Switch or you need to execute raw CLI commands, you can use the Paramiko library. This method establishes an SSH connection and sends commands, then reads the text-based output.
How it Works:
- Paramiko creates an SSH client connection to the switch.
- It authenticates using a username and password (or SSH keys).
- It opens an interactive shell (or executes a command directly).
- It sends the CLI command (e.g.,
show interfaces). - It reads the output from the shell, which is plain text.
Key Benefits:
- Universal: Works on virtually any network device with SSH, regardless of API support.
- Full CLI Access: You can run any command you can type at the console.
Key Drawbacks:
- Text Parsing: The output is plain text. You must write complex parsing logic (often using regular expressions) to extract structured data, which is brittle.
- Stateful: The SSH session is stateful, which can be less robust for large-scale automation.
Example: Getting Interface Status with Paramiko
Prerequisites:
- ArubaOS-Switch with SSH enabled.
- A user with CLI access.
- Python installed with the
paramikolibrary (pip install paramiko).
Python Script (get_interfaces_ssh.py):
import paramiko
import time
# --- Configuration ---
SWITCH_IP = "192.168.1.254"
USERNAME = "admin"
PASSWORD = "your_password"
PORT = 22
# --- Main Logic ---
def get_interface_status(hostname, username, password, port):
try:
# Create a new SSH client
ssh_client = paramiko.SSHClient()
# Automatically add the switch's host key (not recommended for production)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print(f"Connecting to {hostname}...")
ssh_client.connect(hostname, port=port, username=username, password=password, timeout=10)
# Create an interactive shell session
shell = ssh_client.invoke_shell()
time.sleep(2) # Wait for the shell to be ready
# Send the command
print("Sending command: 'show interfaces'")
shell.send("show interfaces\n")
time.sleep(3) # Wait for the command to execute and output to be generated
# Read the output
output = shell.recv(65535).decode('utf-8')
# Print the raw output
print("\n--- Raw Output ---")
print(output)
# Close the connection
ssh_client.close()
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
get_interface_status(SWITCH_IP, USERNAME, PASSWORD, PORT)
The NMS Integration Method: Using PySNMP
If your goal is to monitor switch performance (like CPU, memory, interface traffic), you'll likely use the Simple Network Management Protocol (SNMP). The pysnmp library is a great tool for this.
This method involves querying the switch for Management Information Base (MIB) objects.
How it Works:
- You configure the switch with an SNMP "community string" (like a password for read-only access).
- Your Python script uses
pysnmpto send SNMP GET requests to specific OIDs (Object Identifiers) on the switch. - The switch responds with the data associated with that OID.
Example: Getting System Description with PySNMP
from pysnmp.hlapi import *
# --- Configuration ---
SWITCH_IP = '192.168.1.254'
COMMUNITY_STRING = 'public' # Change this to your community string
# --- Main Logic ---
# sysDescr OID
oid = ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'))
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData(COMMUNITY_STRING),
UdpTransportTarget((SWITCH_IP, 161)),
ContextData(),
oid)
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex)-1][0] or '?'))
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
Summary and Recommendation
| Method | Best For | Pros | Cons |
|---|---|---|---|
| REST API | Configuration, automation, and modern integration. | Structured JSON data, stateless, powerful, and well-documented. | Requires a modern OS version. |
| Paramiko (SSH) | Legacy devices, one-off commands, or when no API is available. | Universal CLI access, no special config needed on device. | Brittle text parsing, stateful, slower for bulk operations. |
| PySNMP | Performance monitoring and getting specific MIB data. | Standard for monitoring, efficient for counters. | Can be complex (OIDs), focused on monitoring not configuration. |
Final Recommendation:
For any new automation project with ArubaOS-Switch, start with the REST API. It is the future of network automation and provides the most reliable and maintainable way to interact with your devices. Use Paramiko for quick tasks or when dealing with older hardware, and use PySNMP when you need to pull performance metrics.
