Collect show commands with Python and Netmiko
Run read-only commands across network devices and save the results for review.
When you need software versions, port state or VLAN membership from many switches, run the same read-only commands on each device and save the output alongside its name.
The script
#!/usr/bin/env python3
import csv, getpass, pathlib
from concurrent.futures import ThreadPoolExecutor
from netmiko import ConnectHandler
COMMANDS = ["show version | include Version", "show interfaces status | include notconnect"]
PASSWORD = getpass.getpass()
OUT = pathlib.Path("out"); OUT.mkdir(exist_ok=True)
def collect(row):
dev = {"device_type": row["type"], "host": row["ip"], "username": "audit", "password": PASSWORD}
try:
with ConnectHandler(**dev) as c:
text = "\n".join(f"### {cmd}\n{c.send_command(cmd)}" for cmd in COMMANDS)
(OUT / f"{row['name']}.txt").write_text(text)
return row["name"], "ok"
except Exception as e:
return row["name"], f"error: {e}"
with open("devices.csv") as f, ThreadPoolExecutor(max_workers=16) as pool:
for name, status in pool.map(collect, csv.DictReader(f)):
print(f"{name:20} {status}")
The devices.csv file has three columns: name,ip,type. Use Netmiko device types such as cisco_ios, mikrotik_routeros or juniper_junos.
Reviewing the results
grep -l "15.2(4)E" out/*.txt # list devices reporting the older release
grep -c notconnect out/*.txt | sort -t: -k2 -n
Permissions
Use a dedicated account that can run inspection commands. Limit its privileges so a future change to the script cannot accidentally reconfigure a device.