csv.DictReader, filtering rows & clean Netmiko dictionaries
Read the inventory from a file
Lesson 3 of 20 · 12 min · Module 1: First steps with automation
Addresses typed into a script go stale. Teams keep an inventory file instead, and every script reads it.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Read a CSV file row by row
- Filter rows on their columns
- Pass Netmiko only the keys it knows
The idea
csv.DictReader reads a CSV file and gives each row as a dictionary keyed by the header line, so row["site"] reads the site column. Filter rows with an if on those columns. Inventory columns such as site and role are for you, not for Netmiko: ConnectHandler accepts only its own parameter names and raises TypeError for any other key. Build a clean dictionary for each device.
import csv
with open("devices.csv") as f:
for row in csv.DictReader(f):
print(row["name"], row["site"], row["role"])
01Each row is a dictionary
DictReader uses the first line of the file as the keys. Every value is a string, even numbers.
import csv
import os
with open("devices.csv") as f:
rows = list(csv.DictReader(f))
print(len(rows))
print(rows[0])6
{'name': 'core1', 'host': '10.0.0.1', 'device_type': 'cisco_ios', 'site': 'bucharest', 'role': 'core'}02Extra keys break ConnectHandler
Passing a whole row fails: Netmiko has no parameter called name, site or role. The error names the first key it did not expect.
from netmiko import ConnectHandler
try:
ConnectHandler(**rows[0], username=os.environ["NET_USERNAME"],
password=os.environ["NET_PASSWORD"])
except TypeError as error:
print(error)BaseConnection.__init__() got an unexpected keyword argument 'name'03Filter, then build a clean dictionary
A list comprehension can filter and build in one step. Only the columns Netmiko needs go into the new dictionary.
cluj = [{"device_type": r["device_type"], "host": r["host"]}
for r in rows if r["site"] == "cluj"]
print(cluj)[{'device_type': 'cisco_ios', 'host': '10.0.1.11'}, {'device_type': 'huawei', 'host': '10.0.1.12'}]Your turn
devices.csv and keep the access switches in Bucharest (role access, site bucharest). Build access_switches: a list of Netmiko dictionaries in file order, each with exactly the keys device_type, host, username and password. Then connect to each one and print its prompt.What the checks look for
- access_switches has the three Bucharest access switches
- Each dictionary has only the Netmiko keys
- Device types come from the file
- Connected to each access switch, and only to them
- The prompts are printed
Take this with you
Keep the inventory in a file, filter rows by their columns, and give Netmiko only its own parameters.
Go a little further
Put the site and role you want in two variables at the top, and print how many devices matched.