Python Paramiko - 在退出之前等待传递的命令的更多输出

Python Paramiko - wait on more output from passed command before exiting

我有以下代码

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
privatekeyfile = 'PK_FILE_PATH'
username ="USERNAME"
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
client.connect(hostname= IP, username=username, pkey=mykey)
command = SERVER_COMMAND

stdin, stdout, stderr = client.exec_command(command)
while not stdout.channel.exit_status_ready():
  if stdout.channel.recv_ready():
    stdoutLines = stdout.readlines()
print stdoutLines

我正在执行的命令在服务器上 运行 大约需要 10 秒。它最初 return 提供了一些信息(用户配置文件和模块版本),然后 运行 提供了一些代码来检查某些本地服务器资源的状态。

Paramiko 在收到初始 header 信息后正在关闭连接。我需要它来等待服务器端命令的完整输出到 return。我试过实施 tintin's solution here, with the same result

有什么想法吗?

Paramiko is closing the connection after it receives the initial header information.

我认为那不是真的。尝试 运行 像

这样的命令
command = 'echo first && sleep 60 && echo second'
while not stdout.channel.exit_status_ready():
  if stdout.channel.recv_ready():
    stdoutLines = stdout.readlines()
    print stdoutLines

你会得到这两行(另请注意,我在循环中打印行,所以你可以看到行)。

一定是你的命令,比如:

  • 该命令在 stderr 上打印最终输出,而不是 stdout
  • 在没有 TTY 的情况下执行时,该命令不会打印最终输出。
  • 该命令是在后台执行子命令的脚本,因此脚本在子命令之前完成。

添加get_pty=True 这将等到命令执行完成。 stdin,stdout,stderr = self.ssh.exec_command(command,get_pty=True)