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