Automating Cisco Switch Serial Number Extraction with Python

Introduction:

In network administration, keeping track of hardware serial numbers is essential for inventory management, support, and warranty purposes. Manually retrieving these serial numbers from multiple switches can be time-consuming. Fortunately, with Python and the Paramiko library, you can automate the extraction of serial numbers from Cisco switches, saving time and reducing the risk of errors. This post walks you through a Python script designed to ping switches, connect via SSH, and extract only the switch's serial number (excluding SFPs or other connected devices), storing the results in an Excel file.

Prerequisites:

Before running the script, ensure you have the following:

  1. Python Installed: Make sure Python is installed on your machine. You can download it from python.org.
  2. Paramiko Library: Paramiko is a Python library used for making SSH connections. Install it using pip:
    pip install paramiko
  3. Openpyxl Library: This library is used to create and manipulate Excel files. Install it using pip:
    pip install openpyxl
  4. Switch Access: Ensure you have SSH access to the Cisco switches, with the correct username and password. The account should have at least read-only access.
  5. IP Address List: Prepare a text file containing the IP addresses of the switches you want to query. Save it as Aug2024.txt in the same directory as the script.

Script Explanation:

  1. Ping the Switches: The check_switch function sends 4 ping packets to each switch to verify it's reachable before attempting to connect via SSH.
  2. Extract Serial Number: The extract_switch_serial function processes the output from the show inventory command, specifically extracting the serial number associated with the switch itself.
  3. Save to Excel: The save_to_excel function creates an Excel workbook, writes the IP addresses and serial numbers to it, and saves the file with a timestamp in its name.
  4. Main Function: This function orchestrates the entire process, reading IPs from Aug2024.txt, connecting to each switch, extracting the serial number, and saving the results to an Excel file.

Running the Script:

  1. Prepare the Environment: Ensure your Python environment has the necessary libraries installed and that your switches are reachable via SSH.
  2. Run the Script: Execute the script from your command line or IDE. You’ll be prompted for your SSH password. The script will then ping each switch, extract the serial number, and save the results in an Excel file.
  3. Check the Output: After the script completes, navigate to D:\Python\Backup\SerialNumbers (or your specified directory) to find the Excel file with the serial numbers.

Full Script

import paramiko
import getpass
import time
import openpyxl
import os
from datetime import datetime

def check_switch(ip):
    response = os.system(f"ping -n 4 {ip}")  # Use '-n 4' for Windows ping command
    return response == 0  # Returns True if the IP is reachable, False otherwise

def extract_switch_serial(output):
    serial_number = None
    for line in output.splitlines():
        if line.startswith("PID:") and "SN:" in line:
            parts = line.split(",")
            for part in parts:
                if "SN:" in part:
                    serial_number = part.split("SN:")[1].strip()
                    return serial_number
    return "Serial number not found"

def save_to_excel(data, excel_file):
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = "Switch Serial Numbers"
    
    # Headers
    sheet.append(["IP Address", "Serial Number"])

    # Data
    for entry in data:
        sheet.append(entry)

    workbook.save(excel_file)

def main():
    # Create a timestamp-based filename
    timestr = datetime.now().strftime("%Y%m%d_%H%M%S")
    my_dir = "D:\\Python\\Backup\\SerialNumbers"  # Update the path as needed
    if not os.path.exists(my_dir):
        os.makedirs(my_dir)
    fname = os.path.join(my_dir, f"SwitchSerials_{timestr}.xlsx")

    # Get Username and Password
    username = "readonly"
    password = getpass.getpass("Enter Password:")

    # Prepare data to be saved to Excel
    data = []

    # Open file with list of switches
    with open("Aug2024.txt") as f:  # Update with the actual file name
        for line in f:
            ip_address = line.strip()

            # Ping the switch with 4 packets before connecting
            if not check_switch(ip_address):
                print(f"{ip_address} is not reachable. Moving to the next IP...")
                continue

            try:
                ssh_client = paramiko.SSHClient()
                ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh_client.connect(hostname=ip_address, username=username, password=password)

                print("Successful connection to", ip_address)

                remote_connection = ssh_client.invoke_shell()
                remote_connection.send("terminal length 0\n")
                time.sleep(1)

                # Run the 'show inventory' command
                remote_connection.send("show inventory\n")
                time.sleep(5)
                inventory_output = remote_connection.recv(65535).decode('utf-8')

                # Extract the switch serial number
                switch_serial_number = extract_switch_serial(inventory_output)
                print(f"Switch Serial Number for {ip_address}: {switch_serial_number}")

                # Save the IP and serial number
                data.append([ip_address, switch_serial_number])

                ssh_client.close()
            except Exception as e:
                print(f"An error occurred while connecting to {ip_address}: {e}")

    # Save data to Excel
    save_to_excel(data, fname)
    print(f"Data saved to {fname}")

if __name__ == "__main__":
    main()

Conclusion:

Automating the retrieval of serial numbers from Cisco switches not only saves time but also ensures accurate documentation. This Python script provides a robust solution for network administrators, especially when managing large-scale network environments. With minor modifications, this script can be adapted to suit various other network devices or different inventory tasks.