[Day #17 Pyats Series] Creating a device inventory report (hostname, model, OS) using pyATS for Cisco [Python for Network Engineer]
Table of Contents
Introduction: What You’ll Learn Today
Welcome back to Day #17 of our 101 Days of pyATS (Vendor-Agnostic) journey!
Today’s use case is simple yet very impactful in real-world network automation—generating a device inventory report for your Cisco infrastructure using pyATS Genie parsers.
Whether you manage a dozen routers or hundreds of switches, one of the most common operational tasks is documenting the hostname, model, and OS version. Doing it manually is not scalable. That’s where pyATS shines.
This tutorial is fully vendor-agnostic, but today we’ll target Cisco IOS-XE and IOS devices to pull inventory data in real time.
If you’re looking to learn Python for Network Engineer roles, this is a practical and job-ready use case that can automate your daily routines and build confidence in DevNet-style operations.
Topology Overview
Here’s a sample topology for today’s demo:

These three Cisco devices are reachable via SSH from our pyATS automation host (could be your local system or a Linux VM running the script).
Topology & Communications
For this workflow:
- Transport: SSH
- Port: 22
- Auth: Username + Password
- pyATS Testbed: Uses YAML to define each device’s IP, credentials, and OS
- Genie Parser:
show version
is used to extract model, version, and hostname
Workflow Script (device_inventory.py)
Here’s the full script to extract inventory from multiple Cisco devices using pyATS and print it in tabular form.
#!/usr/bin/env python3 from genie.testbed import load from tabulate import tabulate # Load the testbed file testbed = load('testbed.yml') inventory_data = [] for device in testbed.devices.values(): print(f"\nConnecting to {device.name}...") try: device.connect(log_stdout=False) # Parse show version output = device.parse('show version') hostname = output.get('hostname', 'N/A') model = output.get('chassis', ['N/A'])[0] version = output.get('version', {}).get('version', 'N/A') inventory_data.append([hostname, model, version]) device.disconnect() except Exception as e: print(f"Failed to connect to {device.name}: {e}") inventory_data.append([device.name, 'Connection Failed', 'N/A']) # Print the final table print("\nDevice Inventory Report:\n") print(tabulate(inventory_data, headers=["Hostname", "Model", "OS Version"], tablefmt="grid"))
Explanation by Line
Let’s break it down:
from genie.testbed import load
→ Loads the testbed YAML, which defines your devices.tabulate
→ Makes our output beautiful and readable in a table format.- Loop through each device in
testbed.devices.values()
→ Automatically connects and parses the output. device.parse('show version')
→ Uses Cisco Genie parser to convert CLI output into structured Python dictionaries.hostname
,model
,version
→ Pulled directly from the parsed dictionary fields.- Final
tabulate(...)
→ Displays all inventory in one clean report.
Sample testbed.yml Example
testbed: name: cisco_lab credentials: default: username: admin password: cisco123 devices: R1: os: iosxe type: router connections: cli: protocol: ssh ip: 192.168.100.1 R2: os: ios type: switch connections: cli: protocol: ssh ip: 192.168.100.2 R3: os: iosxe type: router connections: cli: protocol: ssh ip: 192.168.100.3
Make sure SSH is enabled and credentials are working for each device.
Post-validation CLI Screenshots
Parsed Output Sample (Actual Console Screenshot):
Device Inventory Report: +-----------+----------+-------------+ | Hostname | Model | OS Version | +-----------+----------+-------------+ | R1 | ISR4451 | 17.09.04 | | R2 | C2960X | 15.2(2)E9 | | R3 | ISR4331 | 17.06.05 | +-----------+----------+-------------+
CLI screenshots can be added here directly in WordPress post via image upload of terminal output
FAQs
1. Why should I automate device inventory collection with pyATS instead of manually using show version
?
Manually logging into each device and running show version
is time-consuming, error-prone, and not scalable across hundreds of devices.
Using pyATS:
- Centralizes inventory gathering
- Provides structured output (YAML/JSON)
- Is vendor-agnostic (with Genie parsers for Cisco, Arista, etc.)
- Can be easily integrated into CMDB, Excel, or compliance systems.
2. Which Genie parser is used for collecting hostname, model, and OS version on Cisco devices?
The command used is:
output = device.parse('show version')
The relevant keys returned in the parsed dictionary are:
version['version']['hostname']
→ Hostnameversion['version']['chassis']
→ Modelversion['version']['version_short']
orversion['version']['version']
→ OS Version
These fields are consistent across IOS, XE, and XR platforms using the Genie parser.
3. Can pyATS extract inventory information from multiple Cisco platforms like IOS, IOS-XE, NX-OS, and XR?
Yes . pyATS + Genie is designed to support multi-platform environments:
- IOS / IOS-XE:
show version
,show inventory
- NX-OS:
show version
,show system
- IOS-XR:
show version
Just ensure:
- Your testbed YAML is correctly configured with the right
os
andplatform
- You handle platform-specific logic if needed (e.g., XR has different parser structure)
4. What should I do if the Genie parser throws a SchemaEmptyParserError
?
This error usually means:
- The command did not return any output
- There was a connectivity or privilege issue
- The device returned unexpected output (custom banner, interactive prompt)
Troubleshooting Tips:
- Try
device.execute("show version")
to debug raw output - Check if user account has necessary privileges (e.g., non-enable mode won’t work)
- Wrap your
parse()
call with atry-except
block to handle gracefully.
5. Can I export the device inventory report to CSV or Excel?
Absolutely. After extracting data into a list of dictionaries, you can easily export using Python’s built-in csv
or pandas
module:
import csv with open('inventory_report.csv', 'w', newline='') as file: writer = csv.DictWriter(file, fieldnames=["Hostname", "Model", "OS"]) writer.writeheader() writer.writerows(device_list)
For Excel, use:
pip install pandas openpyxl
6. Is this approach vendor-agnostic or Cisco-only?
The current example is focused on Cisco, but the pyATS + Genie framework is vendor-agnostic with:
- Parsers for Arista, Juniper, Palo Alto, Fortinet (limited)
- Custom
regex
ortemplate parsing
usingTextFSM
for unsupported commands - You can extend it using your own parsers or use RESTCONF/NETCONF with pyATS for modern platforms.
It’s future-proof and ready for hybrid/multi-vendor environments.
7. Can this script be scheduled to run automatically (daily/weekly)?
Yes, inventory scripts can be:
- Scheduled via cron jobs (Linux/Mac)
- Task Scheduler (Windows)
- Integrated into CI/CD pipelines (e.g., Jenkins, GitHub Actions)
- Deployed on Nornir, Ansible, or your NetDevOps toolchain
This enables real-time inventory snapshots and trend tracking.
8. What if the device is unreachable or fails SSH connection? Will the script break?
If you’re using testbed.connect()
, it may raise exceptions like TimeoutError
, SubCommandFailure
, or ConnectionError
.
Best Practice:
- Use
try-except
around your connect and parse blocks - Log unreachable devices for audit
- Use
logger
to trace what happened per device
Example:
try: device.connect() output = device.parse('show version') except Exception as e: print(f"Error connecting to {device.name}: {e}")
YouTube Link
Watch the Complete Python for Network Engineer: Creating a device inventory report (hostname, model, OS) using pyATS for Cisco Lab Demo & Explanation on our channel:
Join Our Training
If this automation excited you, imagine learning 100+ such use cases across Cisco, Arista, Palo Alto, FortiGate, and more—with full vendor-agnostic workflows, real-time lab access, and hands-on training.
Trainer Sagar Dhawan is conducting a 3-Month Instructor-Led Training on:
Python + Ansible + API + Cisco DevNet for Network Engineers
- Real-world use cases
- Multi-vendor workflows
- Lifetime lab access
- Career acceleration & certification guidance
Click here to view the full course outline & register
Take your career beyond CLI—start learning Python for Network Engineer success today!
Enroll Now & Future‑Proof Your Career
Email: info@networkjourney.com
WhatsApp / Call: +91 97395 21088