Connecting to Devices with Python
Lab Objectives
- Learn how to use Netmiko and Python to SSH to a router and run show commands.
- Capture and programmatically parse command output (extract interfaces that are "up/up") and save results to a file.
- Understand why automating simple show workflows is useful in production networks (fast verification, auditing, and troubleshooting).
Tip: Think of automation like a microscope for your network — it lets you quickly examine many devices with the same procedure so you find patterns or problems faster.
ASCII Topology (BASE LAB TOPOLOGY — exact IPs shown)
[Internet]
203.0.113.1
|
R1 (Gateway)
Gi0/0: 10.10.10.1
Gi0/1: 10.10.20.1
Gi0/2: 10.10.30.1
/ | \
R2 R3 R4
Gi0/0: 10.10.10.2 | Gi0/0: 10.10.30.2
Gi0/1: 10.10.40.1 |
/ \ |
S1 S2 S3
/ \ | / \
PC1 PC2 PC3 PC4 PC5
Credentials for examples in this lesson:
- Username: khawar
- Password: Lab@123
Lab Tasks (Try It Yourself First!)
Complete these tasks WITHOUT looking at the solution below. Use
?andshowcommands on the router to learn the syntax.
Task 1: Connect to R1 and run a show command
Using Python + Netmiko, SSH to R1 (10.10.10.1) and run show ip interface brief. Do not change any router configuration — only retrieve information.
Parameters: host 10.10.10.1, username khawar, password Lab@123.
Task 2: Parse the output
From the output captured in Task 1, programmatically produce a list of interfaces whose Status and Protocol are both "up". Print that list to the console.
Task 3: Save the result
Write the parsed list (interfaces that are up/up) to a local file named R1_up_interfaces.txt on your Admin PC.
Think About It: Why is extracting "up/up" interfaces automatically useful in an operations environment? (Hint: consider large environments with hundreds of devices.)
Lab Solution
Task 1 Solution: Connect to R1 and run a show command
What we are doing: Use Netmiko to create an SSH session to R1 and execute show ip interface brief. Netmiko's ConnectHandler wraps SSH, sends the command, and returns the full text output.
from netmiko import ConnectHandler
device = {
'device_type': 'cisco_ios',
'host': '10.10.10.1',
'username': 'khawar',
'password': 'Lab@123',
'port': 22,
}
net_connect = ConnectHandler(**device)
output = net_connect.send_command('show ip interface brief')
print(output)
net_connect.disconnect()
-
What the commands do:
- The Python dictionary defines the device connection parameters.
ConnectHandler(**device)opens an SSH session to the router.send_command('show ip interface brief')executes the show command and returns the router output as text.disconnect()closes the SSH session.
-
Why this matters:
- Automating retrieval reduces manual work and eliminates repetitive CLI typing.
- Netmiko handles SSH negotiation and command timing so you can focus on parsing and automation logic.
Verify:
Run the script; expected console will show the full show ip interface brief output for R1. Example (complete output):
Interface IP-Address OK? Method Status Protocol
GigabitEthernet0/0 10.10.10.1 YES manual up up
GigabitEthernet0/1 10.10.20.1 YES manual up up
GigabitEthernet0/2 10.10.30.1 YES manual up up
GigabitEthernet0/3 unassigned YES unset administratively down down
Loopback0 unassigned YES unset down down
Real-world note: In production, you might run this script nightly across many devices to ensure critical links are operational.
Task 2 Solution: Parse the output
What we are doing: Split the output into lines, ignore the header, and select interfaces whose Status and Protocol fields are both "up". This gives a short list of operational interfaces.
# (continuing after obtaining 'output' from send_command)
up_interfaces = []
for line in output.splitlines():
if line.startswith("Interface") or line.strip() == "":
continue
parts = line.split()
# Interface name is parts[0], IP is parts[1], Status at -2, Protocol at -1
iface = parts[0]
status = parts[-2]
proto = parts[-1]
if status == "up" and proto == "up":
up_interfaces.append(iface)
print("Interfaces that are up/up:", up_interfaces)
-
What the commands do:
splitlines()breaks the output into individual lines.line.split()tokenizes fields separated by whitespace.- We inspect the last two tokens for status and protocol because the column spacing may vary.
- Matching both "up" ensures both the interface and the protocol are operational.
-
Why this matters:
- Parsing text into structured data allows downstream automation (alerting, CMDB updates, dashboards).
Verify: Expected printed output:
Interfaces that are up/up: ['GigabitEthernet0/0', 'GigabitEthernet0/1', 'GigabitEthernet0/2']
Task 3 Solution: Save the result
What we are doing: Write the list of up/up interfaces to a file R1_up_interfaces.txt for record keeping or later processing.
with open('R1_up_interfaces.txt', 'w') as f:
for iface in up_interfaces:
f.write(iface + '\n')
print("Saved R1_up_interfaces.txt")
-
What the commands do:
- Opens (or creates) a file and writes one interface per line.
- This produces an audit trail and can be ingested by other tools.
-
Why this matters:
- Persistent output enables historical trending and provides evidence for change control.
Verify: Console will show:
Saved R1_up_interfaces.txt
File contents (R1_up_interfaces.txt):
GigabitEthernet0/0
GigabitEthernet0/1
GigabitEthernet0/2
Troubleshooting Scenario
Scenario: SSH connection fails when running the script
Symptom: The Python script raises a connection error or times out when connecting to 10.10.10.1.
Your task: Find and fix the issue.
Hint: Often the cause is a typo in the IP address, trailing spaces in a devices file, or incorrect credentials.
Solution:
- From your Admin PC, verify network reachability:
- Ping 10.10.10.1 from your workstation (or verify routing to that subnet).
- Confirm the username and password are correct (username: khawar, password: Lab@123).
- If you are using a devices text file, ensure each line contains a properly formatted IP (no extra spaces). For example, a bad entry like
10.10.10. 1will fail; change to10.10.10.1. - After correction, rerun the script; success will show
show ip interface briefoutput.
Warning: Incorrect credentials will produce an authentication failure. Always confirm account details before troubleshooting connectivity.
Verification Checklist
- SSH to R1 using Netmiko returns
show ip interface briefoutput. - Script correctly prints the list of interfaces that are
up/up. - File
R1_up_interfaces.txtexists and contains one interface per line.
Common Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Script times out connecting to 10.10.10.1 | Wrong IP in script or devices file (extra spaces or bad digits) | Correct the IP entry, remove trailing spaces, re-run the script |
| Authentication failure | Incorrect username/password | Confirm credentials (username: khawar, password: Lab@123) and update the script |
| Parsing returns empty list despite interfaces being up | Script assumed fixed column positions instead of tokenizing | Use split() and inspect last tokens (status and protocol) to be robust |
Challenge Task
Extend your script to read a file devices.txt containing multiple device IPs (one per line), SSH into each device, run show ip interface brief, and produce a single CSV file interfaces_status.csv with columns: device,interface,ip,status,protocol. Do this without step-by-step guidance — reuse the parsing approach you built above.
Real-world insight: Automating multi-device inventory checks is how network teams scale operations. Once you can reliably collect and parse outputs, you can feed them into monitoring systems, CMDBs, or automated remediation routines.