š» 3.1 Construct Python Scripts Using Cisco SDKs
What is a Cisco SDK?
A Software Development Kit (SDK) is a collection of software tools, libraries, code samples, and documentation that simplifies working with an API. Cisco provides SDKs for various platforms to help developers quickly integrate Cisco technologies into their applications.
- Simplified API Interaction: Abstract complex API calls into simple Python functions
- Error Handling: Built-in error checking and exception handling
- Authentication: Handles authentication and session management
- Type Safety: Proper data types and validation
- Documentation: Comprehensive guides and examples
- Faster Development: Pre-built functions save development time
Common Cisco SDKs
| SDK Name | Platform | Installation | Use Case |
|---|---|---|---|
| meraki | Cisco Meraki | pip install meraki |
Cloud-managed networking |
| dnacentersdk | Cisco DNA Center | pip install dnacentersdk |
Enterprise network automation |
| pyats | Network Devices | pip install pyats |
Network testing and automation |
| ncclient | NETCONF devices | pip install ncclient |
NETCONF protocol operations |
| vmanage | Cisco SD-WAN | pip install vmanage |
SD-WAN management |
General SDK Usage Pattern
#!/usr/bin/env python3
"""
General Pattern for Using Cisco SDKs
Common workflow for most Cisco SDK implementations
"""
# Step 1: Import the SDK
from cisco_sdk import CiscoAPI
# Step 2: Initialize client with credentials
client = CiscoAPI(
base_url="https://api.cisco.com",
username="admin",
password="password123",
# or use API key
api_key="your-api-key-here"
)
# Step 3: Make API calls using SDK methods
# Instead of raw HTTP requests, use SDK functions
result = client.get_devices()
# Step 4: Process the response
# SDK returns Python objects (dict, list, etc.)
for device in result:
print(f"Device: {device['name']}")
print(f"Status: {device['status']}")
# Step 5: Perform operations
client.update_device(
device_id="123",
config={"enabled": True}
)
# Step 6: Handle errors
try:
client.delete_device("456")
except Exception as e:
print(f"Error: {e}")Example 1: Cisco Meraki SDK
Meraki Cloud-Managed Networking
The Cisco Meraki SDK allows you to programmatically manage Meraki cloud-managed networks.
pip install meraki
Meraki SDK Example - Get Organizations and Networks
#!/usr/bin/env python3
"""
Cisco Meraki SDK Example
Demonstrates how to use Meraki SDK to retrieve organization and network info
"""
import meraki
# Initialize Meraki Dashboard API client
# Get your API key from: Dashboard > Organization > Settings > Dashboard API access
API_KEY = "your_meraki_api_key_here"
# Create dashboard object
dashboard = meraki.DashboardAPI(
api_key=API_KEY,
print_console=False # Set to True for debugging
)
def get_organizations():
"""Get all organizations"""
try:
print("="*70)
print("CISCO MERAKI - GET ORGANIZATIONS")
print("="*70)
# Get organizations (SDK handles authentication and requests)
organizations = dashboard.organizations.getOrganizations()
print(f"\nā
Found {len(organizations)} organization(s):\n")
for org in organizations:
print(f"Organization ID: {org['id']}")
print(f"Name: {org['name']}")
print(f"URL: {org['url']}")
print("-" * 70)
return organizations
except meraki.APIError as e:
print(f"ā Meraki API Error: {e}")
return None
except Exception as e:
print(f"ā Error: {e}")
return None
def get_networks(organization_id):
"""Get all networks in an organization"""
try:
print("\n" + "="*70)
print(f"NETWORKS IN ORGANIZATION: {organization_id}")
print("="*70)
# Get networks for organization
networks = dashboard.organizations.getOrganizationNetworks(
organizationId=organization_id
)
print(f"\nā
Found {len(networks)} network(s):\n")
for network in networks:
print(f"Network ID: {network['id']}")
print(f"Name: {network['name']}")
print(f"Type: {', '.join(network['productTypes'])}")
print(f"Tags: {', '.join(network.get('tags', []))}")
print("-" * 70)
return networks
except meraki.APIError as e:
print(f"ā Meraki API Error: {e}")
return None
def get_network_devices(network_id):
"""Get all devices in a network"""
try:
print("\n" + "="*70)
print(f"DEVICES IN NETWORK: {network_id}")
print("="*70)
# Get devices
devices = dashboard.networks.getNetworkDevices(networkId=network_id)
print(f"\nā
Found {len(devices)} device(s):\n")
for device in devices:
print(f"Name: {device.get('name', 'Unnamed')}")
print(f"Model: {device['model']}")
print(f"Serial: {device['serial']}")
print(f"MAC: {device.get('mac', 'N/A')}")
print(f"Status: {device.get('status', 'Unknown')}")
print("-" * 70)
return devices
except meraki.APIError as e:
print(f"ā Meraki API Error: {e}")
return None
def update_network_settings(network_id, name=None, timezone=None):
"""Update network settings"""
try:
print("\n" + "="*70)
print(f"UPDATING NETWORK: {network_id}")
print("="*70)
# Prepare update data
update_data = {}
if name:
update_data['name'] = name
if timezone:
update_data['timeZone'] = timezone
# Update network
updated_network = dashboard.networks.updateNetwork(
networkId=network_id,
**update_data
)
print("\nā
Network updated successfully!")
print(f"Name: {updated_network['name']}")
print(f"Timezone: {updated_network.get('timeZone', 'N/A')}")
return updated_network
except meraki.APIError as e:
print(f"ā Meraki API Error: {e}")
return None
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
# Get organizations
orgs = get_organizations()
if orgs:
# Use first organization
org_id = orgs[0]['id']
# Get networks in organization
networks = get_networks(org_id)
if networks:
# Get devices in first network
network_id = networks[0]['id']
devices = get_network_devices(network_id)
- Simple Authentication: Just provide API key
- Organization Management: List and manage organizations
- Network Operations: Create, read, update, delete networks
- Device Management: Monitor and configure devices
- Client Tracking: View connected clients
- SSID Configuration: Manage wireless networks
Example 2: Cisco DNA Center SDK
DNA Center Enterprise Network Automation
The Cisco DNA Center SDK provides programmatic access to DNA Center for intent-based networking automation.
pip install dnacentersdk
DNA Center SDK Example
#!/usr/bin/env python3
"""
Cisco DNA Center SDK Example
Demonstrates device and site management operations
"""
from dnacentersdk import DNACenterAPI
# Initialize DNA Center API client
dnac = DNACenterAPI(
username="admin",
password="C1sco12345",
base_url="https://sandboxdnac.cisco.com",
version='2.3.3.0',
verify=False # For sandbox/self-signed certs
)
def get_all_devices():
"""Retrieve all devices from DNA Center"""
try:
print("="*70)
print("DNA CENTER - GET ALL DEVICES")
print("="*70)
# Get devices (SDK method)
devices = dnac.devices.get_device_list()
print(f"\nā
Found {len(devices.response)} device(s):\n")
for device in devices.response[:5]: # Show first 5
print(f"Hostname: {device.hostname}")
print(f"Type: {device.type}")
print(f"IP: {device.managementIpAddress}")
print(f"Serial: {device.serialNumber}")
print(f"Software: {device.softwareVersion}")
print(f"Reachability: {device.reachabilityStatus}")
print("-" * 70)
return devices.response
except Exception as e:
print(f"ā Error: {e}")
return None
def get_device_by_ip(ip_address):
"""Get device details by IP address"""
try:
print("\n" + "="*70)
print(f"GET DEVICE BY IP: {ip_address}")
print("="*70)
# Get device by management IP
device = dnac.devices.get_device_list(
managementIpAddress=ip_address
)
if device.response:
dev = device.response[0]
print(f"\nā
Device found:")
print(f" Hostname: {dev.hostname}")
print(f" Family: {dev.family}")
print(f" Platform ID: {dev.platformId}")
print(f" Role: {dev.role}")
print(f" Up Time: {dev.upTime}")
return dev
else:
print(f"ā No device found with IP: {ip_address}")
return None
except Exception as e:
print(f"ā Error: {e}")
return None
def get_network_health():
"""Get overall network health"""
try:
print("\n" + "="*70)
print("NETWORK HEALTH OVERVIEW")
print("="*70)
# Get network health
health = dnac.topology.get_overall_network_health()
print("\nā
Network Health Status:")
for category in health.response:
print(f"\n{category.get('category', 'Unknown')}:")
print(f" Good Count: {category.get('goodCount', 0)}")
print(f" Bad Count: {category.get('badCount', 0)}")
print(f" Fair Count: {category.get('fairCount', 0)}")
print(f" Total Count: {category.get('totalCount', 0)}")
# Calculate health percentage
total = category.get('totalCount', 0)
good = category.get('goodCount', 0)
if total > 0:
health_pct = (good / total) * 100
print(f" Health: {health_pct:.1f}%")
return health.response
except Exception as e:
print(f"ā Error: {e}")
return None
def get_sites():
"""Get all sites/locations"""
try:
print("\n" + "="*70)
print("GET ALL SITES")
print("="*70)
# Get site hierarchy
sites = dnac.sites.get_site()
print(f"\nā
Found {len(sites.response)} site(s):\n")
for site in sites.response[:10]: # Show first 10
print(f"Name: {site.get('name', 'N/A')}")
print(f"Type: {site.get('additionalInfo', [{}])[0].get('nameSpace', 'N/A')}")
print(f"Site ID: {site.get('id', 'N/A')}")
print("-" * 70)
return sites.response
except Exception as e:
print(f"ā Error: {e}")
return None
def get_client_health():
"""Get client (endpoint) health"""
try:
print("\n" + "="*70)
print("CLIENT HEALTH")
print("="*70)
# Get client health
timestamp = None # Use current time
health = dnac.clients.get_overall_client_health(timestamp=timestamp)
print("\nā
Client Health Status:")
for score in health.response:
print(f"\nScore Category: {score.get('scoreCategory', {}).get('scoreCategory', 'N/A')}")
print(f" Client Count: {score.get('scoreCategory', {}).get('clientCount', 0)}")
print(f" Client Unique Count: {score.get('scoreCategory', {}).get('clientUniqueCount', 0)}")
return health.response
except Exception as e:
print(f"ā Error: {e}")
return None
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
# Get all devices
devices = get_all_devices()
# Get network health
network_health = get_network_health()
# Get sites
sites = get_sites()
# Get client health
client_health = get_client_health()
# Query specific device (example)
if devices:
first_device_ip = devices[0].managementIpAddress
device_detail = get_device_by_ip(first_device_ip)
- Device Management: Discover, inventory, and manage devices
- Site Management: Organize devices by location
- Network Health: Monitor health scores and analytics
- Client Analytics: Track endpoint connections and performance
- Template Programming: Deploy configurations at scale
- Path Trace: Troubleshoot connectivity
Example 3: PyATS (Python Automated Test System)
PyATS Network Testing & Automation Framework
PyATS is Cisco's Python framework for network test automation, providing powerful libraries for connecting to and testing network devices.
pip install pyats[full]
PyATS Example - Device Connection and Commands
#!/usr/bin/env python3
"""
PyATS (Genie) Example
Demonstrates device connection and command execution
"""
from pyats.topology import loader
from genie.conf import Genie
# Sample testbed YAML (saved as testbed.yaml)
testbed_yaml = """
devices:
router1:
type: router
os: iosxe
connections:
cli:
protocol: ssh
ip: 192.168.1.1
port: 22
credentials:
default:
username: admin
password: cisco123
"""
def connect_to_device():
"""Connect to a device using PyATS"""
# Load testbed from YAML
# testbed = loader.load('testbed.yaml')
# For demonstration, we'll show the connection pattern
print("="*70)
print("PyATS - DEVICE CONNECTION")
print("="*70)
# Connect to device
# device = testbed.devices['router1']
# device.connect()
print("""
ā
Device connection established!
Connection Code:
----------------
from pyats.topology import loader
# Load testbed
testbed = loader.load('testbed.yaml')
# Get device
device = testbed.devices['router1']
# Connect
device.connect()
print(f"Connected to {device.name}")
""")
return None
def execute_show_commands():
"""Execute show commands on device"""
print("\n" + "="*70)
print("EXECUTE SHOW COMMANDS")
print("="*70)
print("""
ā
Executing commands:
# Execute a command
output = device.execute('show version')
print(output)
# Execute multiple commands
commands = [
'show ip interface brief',
'show ip route',
'show running-config'
]
for cmd in commands:
print(f"\\nExecuting: {cmd}")
output = device.execute(cmd)
print(output)
""")
def parse_show_commands():
"""Parse show command output using Genie parsers"""
print("\n" + "="*70)
print("PARSE SHOW COMMAND OUTPUT")
print("="*70)
print("""
ā
Using Genie parsers to structure output:
# Parse show version (returns structured dict)
parsed_output = device.parse('show version')
# Access structured data
version = parsed_output['version']['version']
uptime = parsed_output['version']['uptime']
hostname = parsed_output['version']['hostname']
print(f"Hostname: {hostname}")
print(f"Version: {version}")
print(f"Uptime: {uptime}")
# Parse show ip interface brief
interfaces = device.parse('show ip interface brief')
for intf_name, intf_data in interfaces['interface'].items():
ip = intf_data.get('ip_address', 'unassigned')
status = intf_data.get('status', 'unknown')
print(f"{intf_name}: {ip} - {status}")
""")
def learn_device_features():
"""Use Genie learn feature to gather device information"""
print("\n" + "="*70)
print("LEARN DEVICE FEATURES")
print("="*70)
print("""
ā
Learning device configuration and operational state:
# Learn all about interfaces
interface_ops = device.learn('interface')
# Access learned data
for intf_name, intf_obj in interface_ops.info.items():
print(f"Interface: {intf_name}")
print(f" Enabled: {intf_obj.get('enabled', False)}")
print(f" MAC: {intf_obj.get('mac_address', 'N/A')}")
# Learn routing
routing = device.learn('routing')
# Learn OSPF
ospf = device.learn('ospf')
# Learn BGP
bgp = device.learn('bgp')
# Learn entire device (all features)
device_ops = device.learn('all')
""")
def compare_configurations():
"""Compare device configurations using PyATS diff"""
print("\n" + "="*70)
print("CONFIGURATION COMPARISON")
print("="*70)
print("""
ā
Compare before/after configurations:
# Capture baseline
baseline = device.learn('all')
# Make changes...
device.configure('interface GigabitEthernet0/0/0')
device.configure('description TEST_INTERFACE')
# Capture new state
current = device.learn('all')
# Compare (diff)
diff = baseline.diff(current)
# Print differences
print(diff)
# Check if anything changed
if diff:
print("ā ļø Configuration changed!")
print(diff)
else:
print("ā
No changes detected")
""")
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
print("\nš§ PyATS/Genie Framework Demonstration")
print("="*70)
# Show connection
connect_to_device()
# Show command execution
execute_show_commands()
# Show parsing
parse_show_commands()
# Show learning
learn_device_features()
# Show comparison
compare_configurations()
print("\n" + "="*70)
print("ā
PyATS Demonstration Complete!")
print("="*70)
- Device Connection: Support for multiple protocols (SSH, Telnet, REST)
- Command Execution: Run any CLI command
- Parser Library: 1000+ parsers to convert text to structured data
- Learn Feature: Automatically gather operational state
- Diff Engine: Compare configurations and states
- Multi-vendor: Supports Cisco IOS, NX-OS, IOS-XR, ASA, and more
SDK vs Raw API Comparison
| Aspect | Using SDK | Raw API (requests) |
|---|---|---|
| Code Complexity | ā
Simple, readabledevices = client.get_devices() |
ā More complexresponse = requests.get(url, headers=headers) |
| Authentication | ā Handled automatically | ā Manual header management |
| Error Handling | ā Built-in exceptions | ā Manual status code checking |
| Response Parsing | ā Returns Python objects | ā Manual JSON parsing |
| Documentation | ā Method docstrings | ā Refer to API docs |
| Learning Curve | ā Lower | ā Higher |
| Flexibility | ā ļø Limited to SDK features | ā Full API access |
- Read Documentation: Always consult the SDK documentation first
- Use Virtual Environments: Isolate SDK dependencies
- Error Handling: Wrap SDK calls in try-except blocks
- Credentials Security: Never hardcode credentials, use environment variables
- Rate Limiting: Respect API rate limits even with SDKs
- Version Compatibility: Check SDK version matches platform version
š 3.2 Cisco Network Management Platforms and APIs
Overview of Cisco Management Platforms
Cisco provides several network management platforms, each designed for specific use cases and network architectures. These platforms offer centralized management, automation, and programmability through APIs.
1. Cisco Meraki
Meraki Cloud-Managed Networking
Cisco Meraki provides cloud-managed IT solutions for wireless, switching, security, and SD-WAN, all controlled through an intuitive web-based dashboard.
Key Capabilities
- Zero-Touch Deployment: Devices auto-configure when connected to internet
- Cloud Management: Manage networks from anywhere via web dashboard
- Wireless (MR): Access points with seamless roaming and analytics
- Switching (MS): Layer 2/3 switches with cloud monitoring
- Security (MX): Firewall, VPN, content filtering, threat protection
- SD-WAN: Intelligent path selection and failover
- Camera (MV): Smart cameras with built-in storage
- Sensors (MT): Environmental and asset tracking
Meraki Dashboard API
| API Feature | Capability |
|---|---|
| Authentication | API key-based (generated from Dashboard) |
| Endpoints | Organizations, Networks, Devices, Clients, SSIDs |
| Operations | CRUD on networks, configure devices, monitor clients |
| Webhooks | Real-time alerts for network events |
| Rate Limits | 5 requests/second per organization |
https://api.meraki.com/api/v1Documentation: https://developer.cisco.com/meraki
Common Use Cases
- Bulk network and device provisioning
- Guest Wi-Fi management and splash pages
- Client tracking and location analytics
- Automated firewall rule updates
- SD-WAN traffic shaping policies
- Integration with ticketing systems (ServiceNow, Jira)
2. Cisco DNA Center
DNA Center Intent-Based Networking
Cisco DNA Center is the network management and command center for Cisco's intent-based networking (IBN) solution, designed for enterprise campus and branch networks.
Key Capabilities
- Design: Network hierarchy, templates, profiles
- Policy: Group-based policies, application QoS
- Provision: Zero-touch deployment, PnP (Plug and Play)
- Assurance: AI/ML-powered insights, troubleshooting
- Software Image Management (SWIM): Manage and deploy IOS images
- Network Insights: Predictive analytics and health monitoring
- SD-Access: Software-defined access fabric automation
- Automation: Template-based configuration deployment
DNA Center APIs
| API Category | Capabilities |
|---|---|
| Intent API | High-level business intent (create site, assign policy) |
| Integration API | CRUD operations on devices, templates, policies |
| Multivendor API | Support for 3rd-party device management |
| Events & Notifications | Webhooks for network events |
| Command Runner | Execute CLI commands on devices |
https://{dnac-host}/dna/intent/api/v1Authentication: Token-based (OAuth 2.0)
Documentation: https://developer.cisco.com/docs/dna-center
Common Use Cases
- Automated device onboarding (PnP)
- Template-based configuration deployment
- Network health monitoring and alerting
- Software image lifecycle management
- Path trace for troubleshooting
- Site and device inventory management
3. Cisco ACI (Application Centric Infrastructure)
ACI Software-Defined Data Center
Cisco ACI is a software-defined networking (SDN) solution for data centers, providing centralized automation and policy-driven application deployment.
Key Capabilities
- Application Policy: Define policies based on application requirements
- Fabric Automation: Automated underlay and overlay provisioning
- Microsegmentation: Granular security within the data center
- Multi-Tenancy: Logical separation of networks and policies
- Service Graph: Insert services (firewalls, load balancers) in traffic path
- Multi-Cloud: Extend policies to AWS, Azure, Google Cloud
- Integration: VMware, Kubernetes, OpenStack
- Visibility: End-to-end application flow visibility
ACI APIC APIs
| API Type | Description |
|---|---|
| REST API | Full CRUD access to ACI managed objects (MOs) |
| Object Model | Hierarchical structure: Tenant > Application > EPG |
| Query Language | Flexible queries with filters and selectors |
| Subscriptions | WebSocket-based event notifications |
| Python SDK | Cobra SDK for programmatic access |
https://{apic-host}/apiAuthentication: Token-based or certificate
Documentation: https://developer.cisco.com/docs/aci
Common Use Cases
- Automated tenant and EPG provisioning
- Contract (policy) management
- Service graph insertion (L4-L7 services)
- Integration with orchestration tools (Terraform, Ansible)
- Monitoring fabric health and faults
- Multi-cloud policy extension
4. Cisco SD-WAN (vManage)
SD-WAN Software-Defined WAN
Cisco SD-WAN (formerly Viptela) provides cloud-delivered WAN with application-aware routing, security, and centralized management via vManage.
Key Capabilities
- Application-Aware Routing: Route traffic based on app requirements
- Multi-Transport: MPLS, internet, LTE aggregation
- Security: Integrated firewall, IPS, URL filtering
- Cloud OnRamp: Optimize connectivity to SaaS and IaaS
- Zero-Touch Provisioning (ZTP): Automated branch deployment
- Traffic Engineering: Policy-based path selection
- Centralized Policy: Unified policy management
- Analytics: Deep visibility into application performance
vManage REST API
| API Category | Capabilities |
|---|---|
| Configuration | Templates, policies, device settings |
| Monitoring | Real-time statistics, alarms, events |
| Maintenance | Software upgrades, certificate management |
| Troubleshooting | Device diagnostics, packet capture |
| Administration | User management, RBAC, audit logs |
https://{vmanage-host}/dataserviceAuthentication: Session-based or token
Documentation: https://developer.cisco.com/docs/sdwan
Common Use Cases
- Automated branch site provisioning
- Dynamic policy updates based on network conditions
- Integration with ITSM tools for incident management
- Custom dashboards and reporting
- Bulk device onboarding
- Application performance monitoring
5. Cisco NSO (Network Services Orchestrator)
NSO Multi-Vendor Service Orchestration
Cisco NSO is an orchestration platform for managing and automating network services across multi-vendor environments.
Key Capabilities
- Multi-Vendor Support: Cisco, Juniper, Arista, and more
- Service Abstraction: Define services independently of device CLI
- Transaction Engine: ACID (Atomic, Consistent, Isolated, Durable) transactions
- Rollback: Automatic rollback on configuration failures
- Network-Wide Changes: Configure multiple devices simultaneously
- Service Lifecycle: Create, modify, delete services
- Southbound Protocols: NETCONF, RESTCONF, CLI, SNMP
- Northbound APIs: REST, NETCONF, Python, Java
NSO APIs and Interfaces
| Interface | Description |
|---|---|
| RESTCONF | RESTful API for configuration and operational data |
| NETCONF | XML-based protocol for configuration management |
| Python API | Native Python bindings for service development |
| Java API | Java bindings for enterprise integration |
| CLI | Interactive and scripted CLI access |
http://{nso-host}:8080/restconfAuthentication: Basic or token-based
Documentation: https://developer.cisco.com/docs/nso
Common Use Cases
- Service orchestration (L2VPN, L3VPN, firewall services)
- Network-wide configuration changes
- Service provider automation
- Multi-vendor network automation
- Configuration compliance and drift detection
- Integration with OSS/BSS systems
Platform Comparison
| Platform | Primary Use | Deployment | Best For |
|---|---|---|---|
| Meraki | Cloud-managed networks | Cloud (SaaS) | SMB, distributed enterprises, easy deployment |
| DNA Center | Enterprise campus | On-premises appliance | Large enterprise campus, SD-Access |
| ACI | Data center SDN | On-premises (APIC) | Data centers, multi-cloud, microsegmentation |
| SD-WAN | WAN optimization | Cloud or on-prem | Branch connectivity, application performance |
| NSO | Service orchestration | On-premises | Service providers, multi-vendor automation |
- Meraki: Need cloud-managed, zero-touch deployment, simple management
- DNA Center: Enterprise campus with Cisco Catalyst switches
- ACI: Data center needing application-centric policies and SDN
- SD-WAN: Optimizing WAN connectivity across branches
- NSO: Complex service orchestration, multi-vendor environments
š Interactive Python Interpreter
- Write Python code in the editor below
- Click "ā¶ Run Code" to execute
- Output appears in the console below
- Use sample codes for Cisco SDK patterns
- Experiment with platform comparisons