Have you ever wished you could manage your network switches with the click of a button? Well, Python can help! This post guides you through creating a Python script that connects to network switches, runs commands from a list, and saves the results. This automates tasks like configuration changes and backups, saving you time and effort.
For the Better output of commands always use "terminal lenght 0"
import paramiko
import time
import getpass
import datetime
import os.path
import os
from datetime import datetime
timestr = datetime.now().strftime("%d_%m_%Y--%H_%M")
file_name = ""+timestr
#Save output in D Drive
my_dir = "D:\\Python\\commandlist\"
fname = os.path.join(my_dir)
# Get Username and Password
username = "mehfooz"
password=getpass.getpass("Enter Password:")
# Open file with list of switches
f = open ("myswitches.txt")
# Telnet to each switch and cofigure it
for line in f:
ip_address = line.strip()
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", ip_address)
remote_connection = ssh_client.invoke_shell()
# Run command from the list (command.txt)
COMMANDS = open ('command.txt')
for LINES in COMMANDS:
#time.sleep(5)
remote_connection.send(LINES)
time.sleep(5)
readoutput = remote_connection.recv(655350)
saveoutput = open(fname + file_name + ip_address, "wb")
saveoutput.write(readoutput)
#saveoutput.write("\n") print ("Successful configured")
saveoutput.close
ssh_client.close
The script uses Python libraries to connect to the switches and run commands. Here's a simplified explanation of what each part does:
This Python script equips you to automate switch management tasks, saving valuable time and effort. With its ability to connect to switches, execute commands from a list, and save the output, the script streamlines network configuration changes and backups.