Reputation: 547
I have a python script that reads switch hostnames from a txt file (cisco_input.txt) and runs commands on each switch.
if __name__ == '__main__':
username = raw_input('Enter Your username: ')
password = getpass.getpass('Password:')
ip_file = "cisco_input.txt"
#LOG FILE NAME
sys.stdout = Logger("cisco_output.txt")
with open(ip_file) as bf:
ip_list = bf.read().splitlines()
for ip in ip_list:
#START LOOP TO LOGIN TO DEVICES
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
# Automatically add untrusted hosts
remote_conn_pre.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
# initiate SSH connection
remote_conn_pre.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False)
# print "SSH connection established to %s" % ip
# Use invoke_shell to establish an 'interactive session'
remote_conn = remote_conn_pre.invoke_shell()
# print "Interactive SSH session established"
# Strip the initial router prompt
output = remote_conn.recv(500)
# Turn off paging
disable_paging(remote_conn)
#COMMANDS TO SEND
time.sleep(1)
remote_conn.send("\n")
remote_conn.send("en\n")
remote_conn.send(password)
remote_conn.send("\n")
time.sleep(2)
remote_conn.send("show interfaces counters errors | in 1/0/22\n")
time.sleep(3)
remote_conn.send("logout\n")
time.sleep(.5)
output = remote_conn.recv(15000)
print output
#RESTART LOOP
However, I need to be able to read a second variable for the interface and I'm not sure how I would do that. This line is where I need to be able to call my second variable for the interface:
remote_conn.send("show interfaces counters errors | in $INTERFACE\n")
CLARIFICATION: Currently, the script reads in the switch name to run the command on. So right now I have a text file that looks like: switch1 switch2 switch3
This works great when the port I need to run the command on stays the same. But the port is going to be changing for every switch.
So I'd need an input like: switch1 Gi1/1 switch2 Gi1/15 switch3 Gi1/20
Then I need to be able to use the interface as a variable for the command I'm sending: remote_conn.send("show interfaces counters errors | in $INTERFACE\n")
Thank you.
Upvotes: 0
Views: 81
Reputation: 2623
Say you format your file like this (csv, comma-separated value):
switch1, Gi1/1
switch2, Gi1/20
etc...
You can then read it in using csv.reader:
with open(file) as bf:
reader = csv.reader(bf)
ip_list = list(reader)
for switch, interface in ip_list:
# use switch and interface
There is a problem with this however. If your file is large, loading it into memory all at once can be problematic. The following approach ditches the list and just iterates over the csv.reader, only loading into memory a single row at a time.
with open(file) as bf:
reader = csv.reader(
for switch, interface in reader:
# use switch and interface
Upvotes: 1