HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 16 of 20 — Python for Network Engineers
intermediate Chapter 16 of 20

Network Inventory Tools — Building Device Trackers with Python

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

Why Automated Inventory Matters — Accuracy & Compliance

Maintaining an accurate and up-to-date network inventory is a cornerstone of effective network management. Manual tracking of device information—such as IP addresses, hostnames, serial numbers, and firmware versions—is labor-intensive, error-prone, and often results in outdated documentation. For network engineers, especially those working with complex infrastructures, relying on manual methods can lead to discrepancies that compromise troubleshooting, capacity planning, and security compliance.

Automated network inventory Python scripts significantly enhance accuracy by continuously discovering devices and updating records in real-time. They reduce human error, ensure consistency, and enable rapid detection of unauthorized or rogue devices. Furthermore, automation supports regulatory compliance by maintaining detailed, auditable records of network assets, configurations, and changes.

By implementing device inventory automation, network teams can generate comprehensive network discovery Python tools that map the entire infrastructure dynamically. This approach ensures that the organization’s network documentation tool remains current, providing reliable data for decision-making, troubleshooting, and strategic planning. As a result, automation not only saves time but also elevates the reliability of network asset management.

Discovering Devices — CDP/LLDP Neighbours & Subnet Scanning

Discovering network devices is the initial step in building a robust network inventory Python system. This process involves identifying connected devices through protocols like Cisco Discovery Protocol (CDP) and Link Layer Discovery Protocol (LLDP). These protocols enable network devices such as switches and routers to advertise their identity and capabilities to neighbors, providing immediate visibility into the network topology.

Implementing network discovery Python scripts that leverage CDP and LLDP involves querying network devices via SNMP or directly parsing device configurations. For example, using Python libraries such as pysnmp or netmiko, engineers can automate retrieval of neighbor information:

import netmiko

# Example: Retrieve CDP neighbors from a Cisco switch
connection = netmiko.ConnectHandler(
    device_type='cisco_ios',
    host='192.168.1.1',
    username='admin',
    password='password'
)

output = connection.send_command('show cdp neighbors detail')
print(output)
connection.disconnect()

In addition to CDP/LLDP, subnet scanning using Python tools like nmap enables discovery of devices that might not advertise via discovery protocols. By scanning IP ranges, scripts can detect live hosts, open ports, and services, building a comprehensive view of network assets. For example, a simple subnet scan can be performed with the python-nmap library:

import nmap

nm = nmap.PortScanner()
nm.scan('192.168.1.0/24', arguments='-sn')  # Ping scan
for host in nm.all_hosts():
    if nm[host].state() == 'up':
        print(f'Device found: {host}')

This combination of neighbor discovery and subnet scanning forms the backbone of network discovery Python scripts, allowing network engineers to map devices, identify new additions, and verify existing configurations dynamically.

Collecting Device Facts — Hostname, Model, Serial, OS & Uptime

Once devices are discovered, the next step involves collecting detailed device facts essential for comprehensive network documentation. This data includes hostname, device model, serial number, operating system version, and uptime. Gathering this information programmatically helps in maintaining an accurate device inventory Python system that reflects real-time network conditions.

Using Python libraries like Netmiko or NAPALM, engineers can automate SSH sessions to network devices, execute commands, and parse output to extract relevant facts. For example, to retrieve hostname and serial number from Cisco IOS devices:

from netmiko import ConnectHandler

device = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.10',
    'username': 'admin',
    'password': 'password'
}

connection = ConnectHandler(**device)
hostname = connection.send_command('show running-config | include hostname')
serial = connection.send_command('show version | include Serial')
uptime = connection.send_command('show version | include uptime')
os_version = connection.send_command('show version | include Cisco IOS')

connection.disconnect()

print(f'Hostname: {hostname}')
print(f'Serial: {serial}')
print(f'Uptime: {uptime}')
print(f'OS Version: {os_version}')

Parsing command output requires familiarity with device CLI outputs. Regular expressions or text processing libraries like re or textfsm help extract structured data accurately. For example, Networkers Home Blog offers tutorials on parsing network device outputs effectively.

Automating facts collection ensures that network documentation remains current, enabling quick assessments during troubleshooting or audits. It also facilitates the creation of a rich device inventory Python database that supports asset management, capacity planning, and compliance initiatives.

Storing Inventory Data — CSV, SQLite, Excel & CMDB Integration

After collecting detailed device data, storing this information efficiently is critical for accessibility, analysis, and integration. Various storage options cater to different needs, from simple flat files to complex database systems, and integrating with Configuration Management Databases (CMDB) enhances overall network asset management.

CSV and Excel Files: These are suitable for small to medium-sized inventories and easy to generate using Python’s built-in csv and openpyxl libraries. For example, exporting device facts to CSV:

import csv

with open('network_inventory.csv', 'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=['Hostname', 'Model', 'Serial', 'OS', 'Uptime'])
    writer.writeheader()
    for device in devices_list:
        writer.writerow(device)

SQLite: A lightweight, serverless database ideal for scalable inventory management. Using Python’s sqlite3 module, network engineers can create relational databases that support complex queries and data integrity. Example schema design:

import sqlite3

conn = sqlite3.connect('network_inventory.db')
cursor = conn.cursor()

cursor.execute('''
CREATE TABLE devices (
    id INTEGER PRIMARY KEY,
    hostname TEXT,
    model TEXT,
    serial TEXT,
    os_version TEXT,
    uptime TEXT
)
''')
# Inserting data
cursor.execute('''
INSERT INTO devices (hostname, model, serial, os_version, uptime)
VALUES (?, ?, ?, ?, ?)''', (hostname, model, serial, os_version, uptime))
conn.commit()
conn.close()

CMDB Automation: Modern network operations leverage CMDBs like ServiceNow or Micro Focus SM. Python scripts can interact with CMDB APIs (RESTful or SOAP) to automate device record updates, ensuring real-time accuracy. For example, using Python’s requests library:

import requests

cmdb_url = 'https://cmdb.company.com/api/devices'
headers = {'Authorization': 'Bearer your_api_token'}
device_data = {
    'hostname': hostname,
    'model': model,
    'serial': serial,
    'os_version': os_version,
    'uptime': uptime
}
response = requests.post(cmdb_url, json=device_data, headers=headers)
if response.status_code == 201:
    print('Device record added to CMDB')
else:
    print('Failed to update CMDB')

Choosing the appropriate storage method depends on the scale of your network, integration needs, and reporting requirements. Combining these methods, such as exporting CSV files into a central database or syncing with CMDBs, creates a comprehensive network inventory Python ecosystem that supports efficient network management.

Building a CLI Inventory Tool with Click or argparse

Creating a command-line interface (CLI) tool empowers network engineers to execute device discovery, facts collection, and data storage tasks efficiently. Python’s argparse and Click libraries simplify CLI development, enabling parameterized commands, help messages, and automation scripting.

For example, a basic CLI using argparse might look like this:

import argparse

parser = argparse.ArgumentParser(description='Network Inventory Python Tool')
parser.add_argument('--discover', action='store_true', help='Discover network devices')
parser.add_argument('--collect', type=str, help='Collect device facts for specified device')
parser.add_argument('--export', type=str, help='Export inventory data to CSV')

args = parser.parse_args()

if args.discover:
    # Call discovery functions
    print('Starting device discovery...')
elif args.collect:
    # Call facts collection for specified device
    print(f'Collecting facts for {args.collect}...')
elif args.export:
    # Export data to CSV
    print(f'Exporting inventory to {args.export}...')

Using Networkers Home Blog, you can find tutorials on building more advanced CLI tools that include progress indicators, logging, and error handling. Incorporating CLI automation streamlines repetitive tasks, allowing network teams to run inventory scripts on-demand or schedule them via cron jobs.

Scheduling Inventory Scans with Cron & Task Schedulers

Regularly scheduled network inventory scans ensure that device records are current without manual intervention. On Linux systems, cron is the most common scheduler, while Windows environments typically use Task Scheduler. Automating scans via Python scripts involves setting up scheduled jobs that execute inventory Python code at defined intervals—daily, weekly, or based on network changes.

For example, a cron job to run a Python inventory script every night at 2 AM can be added as:

0 2 * * * /usr/bin/python3 /path/to/inventory_script.py --discover --export /path/to/inventory.csv

In Windows, you can create a scheduled task to run the same script with the appropriate arguments. This automation ensures continuous visibility into network devices, reduces manual effort, and provides timely data for security audits and capacity planning.

Moreover, integrating scheduling with logging and email notifications allows alerts on device changes or failures, enhancing proactive network management. Combining cron with email tools like sendmail or Python’s smtplib facilitates comprehensive automation workflows.

Generating Reports — HTML, PDF & Email Notifications

Effective network documentation requires clear, actionable reports. Python offers libraries to generate reports in various formats—HTML, PDF, or email summaries—that can be automated post-inventory scans. This provides stakeholders with readable, shareable insights into network assets.

HTML Reports: Using Python libraries like jinja2 and html modules, you can create dynamic dashboards showing device status, topology maps, and inventory summaries. For example:

from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('network_report.html')
report = template.render(devices=devices_list)
with open('network_report.html', 'w') as f:
    f.write(report)

PDF Reports: Libraries like ReportLab enable PDF generation with custom formatting, tables, and charts. For example, creating a summary PDF:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

c = canvas.Canvas("inventory_report.pdf", pagesize=letter)
c.drawString(100, 750, "Network Inventory Report")
# Add tables or data here
c.save()

Email Notifications: Automate report delivery by attaching generated reports to emails using Python’s smtplib. Example snippet:

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'Network Inventory Report'
msg['From'] = 'admin@networkershome.com'
msg['To'] = 'team@company.com'
with open('network_report.html', 'r') as f:
    html_content = f.read()
msg.add_alternative(html_content, subtype='html')

with smtplib.SMTP('smtp.example.com') as s:
    s.login('user', 'password')
    s.send_message(msg)

Automated report generation and distribution streamline network documentation processes, ensuring teams stay informed about network health and assets.

Practice: Build a Network Inventory Scanner for Your Lab

Applying these concepts, set up a practical project: develop a network inventory scanner tailored to your lab environment. Start with device discovery using CDP/LLDP, then automate facts collection via SSH or SNMP. Store the data in SQLite or export to CSV for analysis.

For example, create a Python script that:

  • Discovers devices via subnet scanning or neighbor protocols.
  • Connects to each device to retrieve hostname, model, serial, OS, and uptime.
  • Stores the collected data in a SQLite database.
  • Generates an HTML report summarizing the inventory.
  • Schedules itself using cron for periodic updates.

By practicing these steps, you will build a comprehensive network inventory Python tool that enhances network visibility and management efficiency. For detailed tutorials, visit Networkers Home Blog or enroll in a specialized course at Networkers Home.

Key Takeaways

  • Automated network inventory Python scripts improve accuracy, reduce manual effort, and support compliance.
  • Discover devices using CDP, LLDP, and subnet scanning techniques for comprehensive network mapping.
  • Gather detailed device facts with SSH-based commands and parse outputs for structured data.
  • Store inventory data efficiently using CSV, SQLite, or integrate with CMDB APIs for centralized asset management.
  • Build CLI tools with argparse or Click to facilitate automation and scheduled tasks.
  • Schedule regular inventory scans with cron or Task Scheduler to maintain up-to-date records.
  • Generate reports in HTML, PDF, or email summaries for clear communication and documentation.
  • Practice building a network inventory scanner to enhance your practical skills and network visibility.
  • Leverage resources from Networkers Home to deepen your understanding of network automation and Python scripting.

Frequently Asked Questions

How can I ensure that my network inventory Python scripts stay updated with network changes?

To keep your network inventory Python scripts current, automate scheduled scans using cron jobs or Windows Task Scheduler. Regular execution ensures new devices are discovered, and device facts are refreshed. Incorporate version control (e.g., Git) to track script updates, and validate outputs periodically. Additionally, implement error handling and logging within your scripts to detect failures or discrepancies promptly. Combining automation with real-time monitoring tools enhances accuracy and reduces manual oversight. For comprehensive guidance, explore tutorials on network discovery Python techniques at Networkers Home Blog.

What are the benefits of integrating network inventory Python with a CMDB?

Integrating network inventory Python with a CMDB automates the synchronization of device data, ensuring that asset records are always current and accurate. This reduces manual data entry, minimizes errors, and accelerates incident response and troubleshooting. It also provides a centralized view of the entire network infrastructure, facilitating compliance, auditing, and capacity planning. Using APIs, Python scripts can automatically add, update, or remove device entries in the CMDB, enabling seamless asset management workflows. Such integration enhances operational efficiency and supports strategic network decisions. Learn more about CMDB automation at Networkers Home Blog.

Which Python libraries are most effective for building network discovery and inventory tools?

Key libraries for building network discovery and inventory tools include Netmiko for SSH automation, Napalm for multi-vendor device management, pysnmp for SNMP operations, and python-nmap for subnet scanning. Additionally, requests facilitates API interactions with CMDBs, while csv and sqlite3 support data storage and export. For parsing CLI outputs efficiently, textfsm is highly recommended. Combining these libraries provides a powerful toolkit for automating network asset discovery, data collection, and management tasks. For detailed tutorials, visit Networkers Home Blog.

Ready to Master Python for Network Engineers?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and 100% placement support.

Explore Course