
Before using a network-device inventory in an automation job, check the CSV for missing fields and duplicate device names. This Python example reads a local file and reports errors. It does not connect to devices or change the source file.
Start with two columns
Save this illustrative inventory as devices.csv. The third line repeats a hostname and the fourth is missing an IP address.
hostname,ip
access-01,192.0.2.10
ACCESS-01,192.0.2.11
edge-01,Validate each record
import csv
import ipaddress
seen_names = set()
errors = []
with open("devices.csv", encoding="utf-8-sig", newline="") as source:
rows = csv.DictReader(source)
if not {"hostname", "ip"}.issubset(rows.fieldnames or []):
raise SystemExit("Expected hostname and ip columns")
for row in rows:
line = rows.line_num
name = (row.get("hostname") or "").strip().lower()
if not name:
errors.append(f"Line {line}: missing hostname")
elif name in seen_names:
errors.append(f"Line {line}: duplicate hostname {name}")
else:
seen_names.add(name)
try:
ipaddress.ip_address((row.get("ip") or "").strip())
except ValueError:
errors.append(f"Line {line}: missing or invalid IP address")
if errors:
print("\n".join(errors))
raise SystemExit(1)
print("Inventory checks passed")Read the result before running automation
With the sample inventory, expect a duplicate hostname on line 3 and a missing or invalid IP address on line 4. Correct the test file and run the script again. The check accepts IPv4 and IPv6 syntax. It does not verify reachability or check whether two rows share an IP address.
Read the Python CSV documentation for details on headers and quoting. For more practice prompts, see the Python automation interview questions.

0 Comments