Python Network Automation with Netmiko and NAPALM
Python gives you full programmatic control over network devices. Netmiko handles SSH connections; NAPALM provides a vendor-neutral API.
Installation
BASH
pip install netmiko napalmNetmiko: Basic Connection
PYTHON
from netmiko import ConnectHandler
device = {
'device_type': 'mikrotik_routeros',
'host': '192.168.1.1',
'username': 'admin',
'password': 'password',
}
with ConnectHandler(**device) as conn:
output = conn.send_command('/ip address print')
print(output)Bulk Configuration Backup
PYTHON
import json
from datetime import date
from netmiko import ConnectHandler
from pathlib import Path
devices = json.load(open('devices.json'))
backup_dir = Path(f"backups/{date.today()}")
backup_dir.mkdir(parents=True, exist_ok=True)
for device in devices:
try:
with ConnectHandler(**device) as conn:
if device['device_type'] == 'mikrotik_routeros':
config = conn.send_command('/export')
elif device['device_type'] == 'cisco_ios':
config = conn.send_command('show running-config')
filename = backup_dir / f"{device['host']}.txt"
filename.write_text(config)
print(f"✓ {device['host']} backed up")
except Exception as e:
print(f"✗ {device['host']}: {e}")NAPALM: Vendor-Neutral API
PYTHON
from napalm import get_network_driver
driver = get_network_driver('ios')
device = driver(
hostname='192.168.1.10',
username='cisco',
password='password'
)
device.open()
# Get structured data
facts = device.get_facts()
print(f"Hostname: {facts['hostname']}")
print(f"Uptime: {facts['uptime']} seconds")
interfaces = device.get_interfaces()
for iface, data in interfaces.items():
status = "UP" if data['is_up'] else "DOWN"
print(f" {iface}: {status} — {data['description']}")
# Config diff before applying
device.load_merge_candidate(filename='changes.txt')
print(device.compare_config())
device.commit_config() # or device.discard_config()
device.close()Network Audit Script
PYTHON
def audit_snmp(devices):
"""Check SNMP is configured on all devices"""
issues = []
for device in devices:
with ConnectHandler(**device) as conn:
output = conn.send_command('/snmp print')
if 'enabled: no' in output:
issues.append(f"{device['host']}: SNMP disabled")
return issuesScheduling and Reporting
Use APScheduler for periodic tasks and send results via email or Slack webhook.
