When managing a network, it's essential to ensure that all your devices, especially switches, are running smoothly. Regular health checks are crucial to detect and address any issues before they escalate. This blog post will guide you through automating the health check process for Cisco switches using Python. The script presented here connects to switches, retrieves critical information like FAN status, CPU, and memory utilization, and logs the results in an Excel file.
Before we dive into the script, make sure you have the following:
pip install paramiko).pip install openpyxl).Aug2024.txt.
import paramiko
import time
import getpass
import datetime
import os
from datetime import datetime
import openpyxl
from openpyxl.styles import PatternFill
def check_switch(ip):
response = os.system("ping -n 4 " + ip) # Send 4 ping packets
return response == 0 # Returns True if the IP is reachable, False otherwise
def extract_fan_status(output):
if "FAN is FAULTY" in output:
return "FAN is FAULTY"
elif "FAN is OK" in output:
return "FAN is OK"
return "Unknown"
def extract_cpu_utilization(output):
for line in output.splitlines():
if "one minute" in line:
return line.split("one minute:")[1].split(";")[0].strip()
return "Unknown"
def extract_memory_utilization(output):
total, used = 0, 0
for line in output.splitlines():
if "Processor Pool Total" in line:
total = int(line.split(":")[1].strip().split()[0])
elif "Used" in line:
used = int(line.split(":")[1].strip().split()[0])
if total > 0:
utilization_percentage = (used / total) * 100 # Calculate memory utilization based on used memory
return f"{utilization_percentage:.2f}%" # Return formatted percentage
return "Unknown"
def save_to_excel(data, excel_file):
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.append(["IP Address", "FAN Status", "CPU Utilization", "Memory Utilization", "Timestamp"]) # Column headers
for entry in data:
sheet.append(entry)
if "FAULTY" in entry[1]:
red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
for cell in sheet[sheet.max_row]: # Apply fill to the last row added
cell.fill = red_fill
workbook.save(excel_file)
def main():
# Use current date and time for the filename
current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
my_dir = r"C:\Python\Backup\Aug2024" # Ensure the path is a raw string
if not os.path.exists(my_dir):
os.makedirs(my_dir)
fname = os.path.join(my_dir, f"Switch_Health_{current_time}.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:
for line in f:
ip_address = line.strip()
if not check_switch(ip_address):
print(f"{ip_address} is not accessible. 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) # Small delay to ensure the command is executed
# FAN Status
remote_connection.send("sh env all\n")
time.sleep(10)
fan_output = remote_connection.recv(65535).decode('utf-8')
fan_status = extract_fan_status(fan_output)
# CPU Utilization
remote_connection.send("show processes cpu\n")
time.sleep(5)
cpu_output = remote_connection.recv(65535).decode('utf-8')
cpu_utilization = extract_cpu_utilization(cpu_output)
# Memory Utilization
remote_connection.send("show processes memory\n")
time.sleep(5)
memory_output = remote_connection.recv(65535).decode('utf-8')
memory_utilization = extract_memory_utilization(memory_output)
# Timestamp
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data.append([ip_address, fan_status, cpu_utilization, memory_utilization, timestamp])
ssh_client.close()
except Exception as e:
print(f"An error occurred while connecting to {ip_address}: {e}")
continue # Move to the next IP in case of an error
# Save data to Excel
save_to_excel(data, fname)
if __name__ == "__main__":
main()
Pinging the Switches: Before attempting to connect to a switch, the script sends 4 ping packets to check if the switch is reachable.
Connecting via SSH: If the switch is reachable, the script uses the Paramiko library to establish an SSH connection.
Extracting Health Information:
sh env all command and checks if the FAN is OK or FAULTY.show processes cpu command and captures the "one minute" CPU utilization.show processes memory command, calculates the memory utilization percentage, and logs the result.Saving the Data: All the extracted information is saved to an Excel file. If any switch's FAN status is FAULTY, the corresponding row is highlighted in red.
Creating a Report: Each time the script is run, it creates a new Excel file with the current date and time as part of the filename.
Customizing the Script
You can customize the script to suit your environment by changing the following:
Automating the health checks of your Cisco switches using Python can save you significant time and help you stay on top of potential issues. The script presented here is a starting point, and you can further enhance it by adding more checks or customizing the existing ones.