From 9d2b7306ca8cf79cd21ac7b5b9a49af414d8a5f3 Mon Sep 17 00:00:00 2001 From: SoulSniper1212 Date: Wed, 5 Nov 2025 14:01:54 -0500 Subject: [PATCH] fix(script): Configure all switches in the loop The configuration logic was incorrectly indented outside the main loop, which resulted in only the last switch being configured. This commit moves the configuration commands inside the loop to ensure each switch is configured sequentially. It also updates the script to Python 3, adds basic error handling for the Telnet connection, and includes a command to save the running configuration. Fixes #14 --- switchloopfile.py | 73 +++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 34 deletions(-) diff --git a/switchloopfile.py b/switchloopfile.py index 64a6086..e05f085 100644 --- a/switchloopfile.py +++ b/switchloopfile.py @@ -1,34 +1,39 @@ -#!/usr/bin/env python - -import getpass -import sys -import telnetlib - -user = raw_input("Enter your username: ") -password = getpass.getpass() - -f = open ('myswitches') - -for line in f: - print "Configuring Switch " + (line) - HOST = line - tn = telnetlib.Telnet(HOST) - - tn.read_until("Username: ") - tn.write(user + "\n") - if password: - tn.read_until("Password: ") - tn.write(password + "\n") - - tn.write("conf t\n") - - for n in range (2,26): - tn.write("vlan " + str(n) + "\n") - tn.write("name Python_VLAN_" + str(n) + "\n") - - tn.write("end\n") - tn.write("exit\n") - - print tn.read_all() - - +#!/usr/bin/env python3 + +import getpass +import sys +import telnetlib + +user = input("Enter your telnet username: ") +password = getpass.getpass() + +for n in range (10,14): + HOST = "10.115.0." + str(n) + print(f"--- Configuring Switch {HOST} ---") + try: + tn = telnetlib.Telnet(HOST) + except Exception as e: + print(f"Error connecting to {HOST}: {e}") + continue + + tn.read_until(b"Username: ") + tn.write(user.encode('ascii') + b"\n") + if password: + tn.read_until(b"Password: ") + tn.write(password.encode('ascii') + b"\n") + + # The following commands are now inside the loop for each switch + tn.write(b"config t\n") + + # Using a different variable for the inner loop to avoid confusion + for vlan_num in range(2,11): + tn.write(b"vlan " + str(vlan_num).encode('ascii') + b"\n") + tn.write(b"name Python_VLAN_" + str(vlan_num).encode('ascii') + b"\n") + + tn.write(b"end\n") + tn.write(b"write\n") + tn.write(b"exit\n") + + # Print the output for the current switch + print(tn.read_all().decode('ascii')) + print(f"--- Finished with Switch {HOST} ---\n") \ No newline at end of file