I have written below code to run 3 command in remote server interactively
But when I checked 3rd command never executed and code stuck here is my code
def execute():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ipaddress', username='user', password='pw')
chan = ssh.invoke_shell() # start the shell before sending commands
chan.send('cd /path to folder/test')
chan.send('\n')
time.sleep(3)
chan.send("ls -l")
chan.send('\n')
buff = ''
while not buff.endswith("test >"):
resp = chan.recv(9999)
# code stuck here after 'path to folder/test >' comes in shell prompt
buff += resp
print resp
print "test"
chan.send("ls -lh")
chan.send('\n')
time.sleep(5)
buff = ''
while not buff.endswith("test >"):
resp = chan.recv(9999)
buff += resp
print resp
if __name__ == "__main__":
execute()
When I ran I got output of ls -l
but ls -lh
never executed my code stuck in first while loop. Anyone please help to resolve my issue
The code has following 2 errors:
The call to channel.recv
is blocking, you should first check if channel has any data to be read or not using channel.recv_ready()
Also don't use buff.endswith("test >")
as a condition.As the file_name might not always be at the last in buff.
Change the while block to following and it will run the way you want
while "test >" not in buff:
if chan.recv_ready():
resp = chan.recv(9999)
# code won't stuck here
buff+=resp
print resp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.