So I am able to ssh into a list of cisco devices stored in a text file. It works great when the device is up and functioning, but it breaks if it times out due to a infinite loop that happens when the Password field never pops up.
The logic of this with the while loops is what is killing my thought process. I know my attempts to fix are vague but this is hard to test as if I get it wrong it locks me out of my account to do this on our network for some time. Any help would be much appreciated.
Current Code:
import paramiko
import time
#*****************************************
#SSH Credentials for logging into routers
bass_host = 'ssh.server.com'
ssh_username = 'username'
ssh_password = 'password'
port = 22
#*****************************************
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(bass_host, port, ssh_username, ssh_password)
#For Intro Show Commands
router_channel = ssh.invoke_shell()
# Ssh and wait for the password prompt.
hostnames = open('/hostlist.txt', 'r').readlines()
hostnames = map(lambda s: s.strip(), hostnames)
for device in hostnames:
command = 'ssh ' + device + '\n'
router_channel.send(command)
buff = ''
while not buff.endswith('Password: '):
resp = router_channel.recv(9999)
buff += resp
# Send the password and wait for a prompt.
router_channel.send('passwordhere\n')
buff = ''
while not buff.endswith('#'):
resp = router_channel.recv(99999)
buff += resp
router_channel.send('terminal length 0\n')
buff = ''
while not buff.endswith('#'):
resp = router_channel.recv(99999)
buff += resp
Area of Concern:
for device in hostnames:
command = 'ssh ' + device + '\n'
router_channel.send(command)
buff = ''
while not buff.endswith('Password: '):
resp = router_channel.recv(9999)
buff += resp
# Send the password and wait for a prompt.
router_channel.send('passwordhere\n')
buff = ''
while not buff.endswith('#'):
resp = router_channel.recv(99999)
buff += resp
router_channel.send('terminal length 0\n')
buff = ''
Attempted:
for device in hostnames:
command = 'ssh ' + device + '\n'
router_channel.send(command)
buff = ''
timeout = time.time() + 8*3
while not buff.endswith('Password: '):
resp = router_channel.recv(9999)
buff += resp
print 'broke'
if time.time() > timeout:
print 'Broke'
break
continue
else:
continue
# Send the password and wait for a prompt.
router_channel.send('passwordhere\n')
buff = ''
while not buff.endswith('#'):
resp = router_channel.recv(99999)
buff += resp
router_channel.send('terminal length 0\n')
buff = ''