[Day #37 Pyats Series] Hardware inventory collection & reporting using pyATS for Cisco [Python for Network Engineer]

[Day #37 Pyats Series] Hardware inventory collection & reporting using pyATS for Cisco [Python for Network Engineer]

Introduction on the Key Points

Welcome back to the “101 Days of pyATS (Vendor-Agnostic)” series—your go-to hands-on lab journal to automate real-world network tasks. On Day #37, we’re diving into a critical yet often manually performed task—hardware inventory collection.

Imagine this: you need to collect hardware serial numbers, model numbers, slot details, fan statuses, and even the chassis PID for 100+ Cisco devices. Doing this manually from the CLI would take days. But using pyATS, we can automate the entire hardware inventory discovery process in less than 5 minutes.

We’ll build a simple and scalable solution that logs into Cisco routers or switches, parses inventory using Genie, and generates structured output in JSON, CSV, or Excel format. If you’re exploring Python for Network Engineer roles, this is one of the most practical use cases that demonstrates real value in enterprise automation.


Topology Overview

Our inventory validation doesn’t require a complex topology. Even one Cisco IOS-XE device is sufficient to demonstrate this use case.

Lab Setup:

  • Device 1: Cisco CSR1000v Router (R1)
  • Optional: Add R2, R3, etc., to scale testing
  • pyATS host: Ubuntu machine, local Python venv

Commands covered:

  • show inventory
  • show version (optional for uptime, model, etc.)

Topology & Communications

  • SSH connectivity is required
  • pyATS connects via testbed YAML
  • All inventory data is parsed and saved into a dictionary for reporting

Workflow Script

Here’s a complete pyATS script to collect and report hardware inventory details using the Genie parser:

#!/usr/bin/env python

from genie.testbed import load
import csv
import os

# Load the testbed
testbed = load('testbed.yml')
device = testbed.devices['R1']

# Connect to device
device.connect(log_stdout=False)

# Parse the 'show inventory' command
inventory = device.parse('show inventory')

# Extract required fields
inventory_data = []
for name, details in inventory['index'].items():
    inventory_data.append({
        'Name': details.get('name'),
        'Description': details.get('description'),
        'PID': details.get('pid'),
        'VID': details.get('vid'),
        'Serial Number': details.get('sn')
    })

# Save to CSV
output_file = 'hardware_inventory_report.csv'
with open(output_file, 'w', newline='') as csvfile:
    fieldnames = ['Name', 'Description', 'PID', 'VID', 'Serial Number']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for row in inventory_data:
        writer.writerow(row)

print(f"\n Inventory data saved to {output_file}")

Explanation by Line

  • testbed = load('testbed.yml'): Loads device details.
  • device.connect(): Opens SSH session.
  • device.parse('show inventory'): Uses Genie to convert CLI to Python dict.
  • We iterate over the index key which contains hardware slots.
  • Important fields like PID, VID, Serial Number, and Name are extracted.
  • The final report is written into a CSV file which can be opened in Excel.

You can extend this to push data into:

  • SQL databases
  • Web APIs
  • Excel with openpyxl
  • REST dashboards

testbed.yml Example

testbed:
  name: Inventory_Collection
  credentials:
    default:
      username: cisco
      password: cisco
devices:
  R1:
    type: router
    os: iosxe
    connections:
      cli:
        protocol: ssh
        ip: 192.168.1.10

This YAML allows you to scale to multiple devices. Just duplicate the R1 section with new hostnames and IPs.


Post-validation CLI Screenshots (Real Expected Output)

Raw CLI: show inventory

NAME: "Chassis", DESCR: "Cisco CSR1000V Chassis"
PID: CSR1000V           , VID: V00  , SN: 9Z0W4RQ8ZZ9

NAME: "Fan Tray", DESCR: "Internal Fan Assembly"
PID: FTRAY-C1           , VID: V01  , SN: FAN1234567

Parsed Output using Genie:

{
  'index': {
    '1': {
      'name': 'Chassis',
      'description': 'Cisco CSR1000V Chassis',
      'pid': 'CSR1000V',
      'vid': 'V00',
      'sn': '9Z0W4RQ8ZZ9'
    },
    '2': {
      'name': 'Fan Tray',
      'description': 'Internal Fan Assembly',
      'pid': 'FTRAY-C1',
      'vid': 'V01',
      'sn': 'FAN1234567'
    }
  }
}

CSV Output:

NameDescriptionPIDVIDSerial Number
ChassisCisco CSR1000V ChassisCSR1000VV009Z0W4RQ8ZZ9
Fan TrayInternal Fan AssemblyFTRAY-C1V01FAN1234567

FAQs

1] What is hardware inventory collection in network automation, and why is it important?

Hardware inventory collection involves retrieving and documenting physical and logical information about network devices — such as:

  • Chassis model and serial number
  • Line cards and modules
  • Power supplies and fans
  • Software/firmware versions
  • Uptime and licensing

It’s critical for:

  • Asset management & audits
  • Lifecycle planning (EOL/EOS)
  • Compliance & regulatory reporting
  • Hardware replacement or RMA tracking
  • Change management baselines

With pyATS and Genie, you can automate this process across multi-vendor infrastructures with precision.


2] Which commands are used to collect hardware inventory using pyATS Genie parsers?

Most commonly used platform commands:

  • Cisco IOS/IOS-XE/NX-OS:
    • show version
    • show inventory
  • Arista EOS:
    • show version
    • show inventory
  • Juniper Junos:
    • show chassis hardware
    • show version

These are parsed like:

output = device.parse("show inventory")

The result is structured JSON, which can be used for reporting, diffing, or normalization.


3] What key information can I extract from a hardware inventory report?

A typical parsed inventory provides:

  • Hostname
  • Chassis Model & PID
  • Serial Numbers (device, modules)
  • Module Slots & Descriptions
  • Transceiver Details
  • Software Version
  • System Uptime
  • Memory & CPU Info (from show version)

This data is valuable for asset tagging, NMS integration, or CMDB updates.


4] Can I collect hardware inventory across vendors (e.g., Cisco + Arista + Juniper) using the same script?

Yes, using pyATS with per-device OS tagging, you can build a single vendor-agnostic inventory script:

if device.os == "iosxe":
    output = device.parse("show inventory")
elif device.os == "eos":
    output = device.parse("show inventory")
elif device.os == "junos":
    output = device.parse("show chassis hardware")

Then, normalize the output fields (model, serial, slot) into a common data model and generate cross-vendor reports (CSV, JSON, XLSX, etc.).


5] How can I export the hardware inventory data into an Excel or CSV report using Python?

After parsing, use Python’s csv or panda to export:

import csv

with open("hardware_inventory.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Hostname", "PID", "Serial", "Slot"])
    for item in parsed_output['slots']:
        writer.writerow([hostname, item['pid'], item['sn'], item['name']])

This allows you to share inventory data with asset managers, procurement teams, or auditors.


6] How can I detect missing or faulty modules using pyATS inventory parsing?

Use parsed show inventory or show chassis hardware to validate:

  • Expected vs actual module slots
  • Any reported hardware as “Not Present” or “Faulty”

Example:

for module in inventory['slot']:
    if module['state'] != 'ok':
        print(f"{module['name']} is in {module['state']} state")

This is especially useful in data center and ISP environments with modular hardware.


7] Can pyATS detect mismatches between intended hardware (golden state) vs actual state?

Yes, using the genie.utils.diff.Diff() tool:

from genie.utils.diff import Diff
diff = Diff(golden_inventory, current_inventory)
diff.findDiff()
print(diff)

This flags any deviations in hardware inventory — great for post-deployment validation, change control, or supply chain compliance.


8] Is it possible to schedule periodic inventory scans and generate delta reports?

Absolutely! You can:

  1. Schedule a pyATS job via cron or CI/CD pipeline
  2. Collect current inventory
  3. Compare it with last known good snapshot using Diff
  4. Email the delta report or upload to dashboard

This allows continuous monitoring of hardware changes, ideal for large-scale enterprise and MSP networks.


Let me know if you’d like to include:

  • Sample parsed outputs
  • YAML testbed
  • CSV report template
  • Visual topology diagram

for your Day # article on Hardware Inventory Collection using pyATS.


YouTube Link

Watch the Complete Python for Network Engineer: Hardware inventory collection & reporting using pyATS for Cisco [Python for Network Engineer] Lab Demo & Explanation on our channel:

Master Python Network Automation, Ansible, REST API & Cisco DevNet
Master Python Network Automation, Ansible, REST API & Cisco DevNet
Master Python Network Automation, Ansible, REST API & Cisco DevNet
Why Robot Framework for Network Automation?

Join Our Training

If you’re finding these examples valuable and want to automate 70–80% of your daily network tasks, it’s time to take a deeper dive with Trainer Sagar Dhawan’s 3-Month Instructor-Led Program on:

  • Python for Network Engineers
  • pyATS & Genie Automation
  • Ansible for Network Automation
  • Cisco DevNet (Netconf, RESTCONF, APIs)
  • Real-time Projects & EVE-NG Topologies
  • Full Career Roadmap with Lab Access

View Full Course Outline Here

This isn’t just another course — it’s a career upgrade. Build your confidence, automate like a pro, and future-proof your skillset with Python for Network Engineer use cases that work across Cisco, Arista, Palo Alto, and Fortinet.

Enroll Now & Future‑Proof Your Career
Emailinfo@networkjourney.com
WhatsApp / Call: +91 97395 21088

Join hundreds of engineers who are now transforming the way they manage networks!