I have search on this site and multiple other locations but I have been unable to resolve my problem of connecting and maintaining ssh session after one command. Below is my current code:
#!/opt/local/bin/python
import os
import pexpect
import paramiko
import hashlib
import StringIO
while True:
cisco_cmd = raw_input("Enter cisco router cmd:")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.221.235', username='nuts', password='cisco', timeout = 30)
stdin, stdout, stderr = ssh.exec_command(cisco_cmd)
print stdout.read()
ssh.close()
if cisco_cmd == 'exit': break
I can run multiple commands but for every commands a new ssh session is created. The above program does not work when I need to configuration mode because ssh session is not reused.Any assistance in resolving this matter is greatly appreciated.
Your loop does that
Move the initialisation and setup outside the loop. EDIT: Moved close()
I used Exscript instead of paramiko and I am now able to get persistent session on IOS device.
Your ssh session will be reused once you move the
connect
andclose
outside of the loop, but eachexec_command()
happens in a new shell (through a new channel), and are unrelated. You will need to format your commands so that they don't require any state from the shell.If I remember correctly, some Cisco devices only allow a single exec, and then close the connection. In that case, you will need to use
invoke_shell()
, and work interactively using thepexpect
module (which you already have imported, but aren't using).You need to create, connect and close connection outside the while loop.