Connect to multiple routers/switches simultaneously to send command sets using Netmiko.
from netmiko import ConnectHandler
devices = [
{"device_type": "cisco_ios", "host": "192.168.1.10", "username": "admin", "password": "password"},
{"device_type": "cisco_ios", "host": "192.168.1.11", "username": "admin", "password": "password"}
]
for device in devices:
print(f"
Connecting to {device['host']}...")
try:
connection = ConnectHandler(**device)
output = connection.send_command("show ip interface brief")
print(output)
connection.disconnect()
except Exception as e:
print(f"Failed to connect to {device['host']}: {e}")
Pull running configurations from network elements and save them locally with timestamped filenames.
from netmiko import ConnectHandler
from datetime import datetime
from pathlib import Path
device = {"device_type": "cisco_ios", "host": "192.168.1.10", "username": "admin", "password": "password"}
backup_dir = Path("network_backups")
backup_dir.mkdir(exist_ok=True)
connection = ConnectHandler(**device)
config = connection.send_command("show running-config")
filename = backup_dir / f"{device['host']}_{datetime.now():%Y%m%d_%H%M%S}.cfg"
filename.write_text(config)
print(f"Backup saved: {filename}")
connection.disconnect()
Audit interfaces across network elements to detect down links or err-disabled ports.
from netmiko import ConnectHandler
device = {"device_type": "cisco_ios", "host": "192.168.1.10", "username": "admin", "password": "password"}
connection = ConnectHandler(**device)
output = connection.send_command("show interfaces status", use_textfsm=True)
for intf in output:
if intf.get('status') in ['notconnect', 'err-disabled', 'disabled']:
print(f"Alert: Interface {intf.get('port')} status: {intf.get('status')}")
connection.disconnect()
Iterate through external inventory source files (CSV) and bulk-execute network queries.
import csv
from netmiko import ConnectHandler
with open("devices.csv") as file:
for device in csv.DictReader(file):
print(f"Connecting to {device['host']}...")
connection = ConnectHandler(**device)
print(connection.send_command("show version")[:300])
connection.disconnect()
Push structured VLAN changes to switches, verify output, and write changes to memory.
from netmiko import ConnectHandler
switches = [
{"device_type": "cisco_ios", "host": "192.168.1.10", "username": "admin", "password": "password"},
{"device_type": "cisco_ios", "host": "192.168.1.11", "username": "admin", "password": "password"}
]
commands = ["vlan 100", "name SERVERS_ZONE"]
for switch in switches:
connection = ConnectHandler(**switch)
print(connection.send_config_set(commands))
connection.save_config()
connection.disconnect()
Generates standardized Cisco IOS configurations from variables using Jinja2 templates.
from jinja2 import Template
template_str = """
hostname {{ hostname }}
interface {{ interface }}
description {{ description }}
ip address {{ ip_address }} {{ subnet_mask }}
no shutdown
"""
data = {
"hostname": "C9300-DIST-01",
"interface": "GigabitEthernet1/0/1",
"description": "Uplink to Core Router",
"ip_address": "10.0.10.1",
"subnet_mask": "255.255.255.252"
}
print(Template(template_str).render(data))
Tests IP reachability across subnets or device inventory concurrently.
import subprocess
from concurrent.futures import ThreadPoolExecutor
devices = ["192.168.1.1", "192.168.1.10", "192.168.1.11", "10.0.0.1"]
def ping(ip):
res = subprocess.run(["ping", "-n", "2", ip], stdout=subprocess.DEVNULL)
return f"{ip} : {'UP' if res.returncode == 0 else 'DOWN'}"
with ThreadPoolExecutor(max_workers=4) as executor:
for result in executor.map(ping, devices):
print(result)
Extracts system resource metrics and triggers alerts for high utilization.
import re
from netmiko import ConnectHandler
device = {"device_type": "cisco_ios", "host": "192.168.1.10", "username": "admin", "password": "password"}
connection = ConnectHandler(**device)
output = connection.send_command("show processes cpu | include CPU utilization")
connection.disconnect()
match = re.search(r"five minutes:\s*(\d+)%", output)
if match:
cpu = int(match.group(1))
print(f"Device: {device['host']} | CPU: {cpu}% | Status: {'HIGH' if cpu > 80 else 'NORMAL'}")
Checks if running configurations comply with security baseline standards.
import re
from netmiko import ConnectHandler
checks = {
"AAA Model": r"aaa new-model",
"SSH v2": r"ip ssh version 2",
"HTTP Disabled": r"no ip http server"
}
device = {"device_type": "cisco_ios", "host": "192.168.1.10", "username": "admin", "password": "password"}
connection = ConnectHandler(**device)
config = connection.send_command("show running-config")
connection.disconnect()
for name, pattern in checks.items():
status = "PASS" if re.search(pattern, config) else "FAIL"
print(f"{name:<20} : {status}")
Aggregates reachability, interface health, resources, and baseline compliance into a report.
import pandas as pd
summary = {
"Metric": ["Devices Up", "Devices Down", "Interfaces Up", "High CPU Warnings"],
"Count": [24, 1, 186, 3],
"Status": ["OK", "ALERT", "OK", "WARN"]
}
df = pd.DataFrame(summary)
df.to_html("network_health_report.html", index=False)
df.to_excel("network_health_report.xlsx", index=False)
print("Health reports generated successfully.")