本文介绍了等待完成使用 Python Paramiko 执行的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Paramiko 中编写了这段代码:

I wrote this code in Paramiko:

ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect(hostname, username=user, password=passwd, timeout=3)

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)

我正在尝试在我的 Linux 服务器上执行更多命令.问题是我的 Python 代码不等待完成执行命令,例如,如果我尝试执行 sleep 30,Python 不会等待 30 秒完成执行命令.如何解决这个问题?我尝试使用 while recv_ready(),但它仍然没有等待.

I'm trying 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 tried with while recv_ready(), but it still does not wait.

推荐答案

使用 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")

以下代码对我有用:

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)

请注意,命令 history 不能按原样使用 ssh 执行.请参阅此处的示例:https://superuser.com/questions/962001/incorrect-output-of-history-command-of-ssh-how-to-read-the-timestamp-info-corre

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

这篇关于等待完成使用 Python Paramiko 执行的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:37