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.
Before running the script, ensure you have the following:
pip install paramiko
pip install openpyxl
Aug2024.txt in the same directory as the script.check_switch function sends 4 ping packets to each switch to verify it's reachable before attempting to connect via SSH.extract_switch_serial function processes the output from the show inventory command, specifically extracting the serial number associated with the switch itself.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.Aug2024.txt, connecting to each switch, extracting the serial number, and saving the results to an Excel file.D:\Python\Backup\SerialNumbers (or your specified directory) to find the Excel file with the serial numbers.
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()
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.