Python for Networking — Looping Over Devices

20 min In Progress

Learning Objectives

  • Build a list of device connection dicts
  • Loop over devices collecting results into one report
  • Handle a failure in one device without crashing the whole run

The Pattern That Matters Most

You don't need to be a software engineer for this -- you need enough Python to connect, send a command, parse the result, and loop over a list of devices. This pattern is literally how you check 50 routers in 30 seconds instead of 50 manual logins.

In a real driver this would be Netmiko's ConnectHandler + send_command -- see ch-network-automation for the full real-driver version.
devices = [
    {"host": "192.168.1.1", "name": "core-sw1"},
    {"host": "192.168.1.2", "name": "edge-rtr2"},
]

def fake_send_command(host, command):
    # stands in for a real Netmiko connection.send_command()
    return f"output of '{command}' from {host}"

for device in devices:
    result = fake_send_command(device["host"], "show version")
    print(f"{device['name']}: {result}")

📝 Exercise: Build a Resilient Multi-Device Runner

Write a function run_on_all(devices, command, runner) that loops over devices, calls runner(device, command), and collects results into a dict {device_name: result}. If runner() raises an exception for one device, catch it, store the error message instead of crashing, and continue to the next device.

code.py
Output

            
← Back to Chapter