python paramiko wait to finish execute command

随声附和 提交于 2019-12-14 01:22:47

问题


I'm write this code in paramiko :

def TryExecute(hostname='192.168.1.1', user='root', passwd='root'):
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect(hostname, username=user, password=passwd, timeout=3)
    #stdin, stdout, stderr =  ssh.exec_command("uname -a")

    session = ssh.invoke_shell()
    session.send("\n")

    session.send("echo step 1\n")
    time.sleep(1)

    session.send("sleep 30\n")
    time.sleep(1)

    while not session.recv_ready():
        time.wait(2)

    output = session.recv(65535)

    session.send("echo step 2\n")
    time.sleep(1)

    output += session.recv(65535)

I'm try execute more commands on my linux server, the problem is my python code not wait to finish execute command, for example if I'm try to execute "sleep 30", the python not wait 30 seconds for finish execute commands, how can resolve this problem ? I'm try whit while recv_ready() bat not wait :(


回答1:


Use exec_command: http://docs.paramiko.org/en/1.16/api/channel.html

stdin, stdout, stderr = ssh.exec_command("my_long_command --arg 1 --arg 2")

The following code works for me:

from paramiko import SSHClient, AutoAddPolicy
import time
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect('111.111.111.111', username='myname', key_filename='/path/to/my/id_rsa.pub', port=1123)
sleeptime = 0.001
outdata, errdata = '', ''
ssh_transp = ssh.get_transport()
chan = ssh_transp.open_session()
# chan.settimeout(3 * 60 * 60)
chan.setblocking(0)
chan.exec_command('ls -la')
while True:  # monitoring process
    # Reading from output streams
    while chan.recv_ready():
        outdata += chan.recv(1000)
    while chan.recv_stderr_ready():
        errdata += chan.recv_stderr(1000)
    if chan.exit_status_ready():  # If completed
        break
    time.sleep(sleeptime)
retcode = chan.recv_exit_status()
ssh_transp.close()

print(outdata)
print(errdata)

Please note that command history cannot be executed with ssh as is. See example here: https://superuser.com/questions/962001/incorrect-output-of-history-command-of-ssh-how-to-read-the-timestamp-info-corre



来源:https://stackoverflow.com/questions/34181078/python-paramiko-wait-to-finish-execute-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!