如果要检查recv_ready(),是否必须检查exit_status_ready?

14 投票
2 回答
26810 浏览
提问于 2025-04-18 05:35

我正在运行一个远程命令,代码如下:

ssh = paramiko.SSHClient()
ssh.connect(host)
stdin, stdout, stderr = ssh.exec_command(cmd)

现在我想获取输出。我见过类似这样的代码:

# Wait for the command to finish
while not stdout.channel.exit_status_ready():
    if stdout.channel.recv_ready():
        stdoutLines = stdout.readlines()

但是有时候这段代码似乎根本不会执行 readlines()(即使应该有数据在标准输出上)。这让我觉得,虽然 stdout.channel.exit_status_ready() 返回 True,但 stdout.channel.recv_ready() 不一定会立刻准备好。

像这样做合适吗?

# Wait until the data is available
while not stdout.channel.recv_ready():
    pass

stdoutLines = stdout.readlines()

也就是说,我真的需要先检查退出状态,然后再等 recv_ready() 表示数据准备好吗?

在我等待 stdout.channel.recv_ready() 变为 True 的时候,怎么知道标准输出上应该有数据呢?(如果没有标准输出的内容,它是不会变为 True 的)

2 个回答

0

ssh.exec_command(cmd)之后加上下面的几行代码。这个循环会一直运行,只要你的 shell 脚本还在执行,等到脚本完成后就会立刻退出。

while int(stdout.channel.recv_exit_status()) != 0:
    time.sleep(1)
48

也就是说,我真的需要在等待 recv_ready() 表示数据准备好之前先检查退出状态吗?

不需要。即使远程进程还没有结束,接收数据(比如 stdout/stderr)也是完全可以的。而且,有些 sshd 实现甚至不提供远程进程的退出状态,这样你可能会遇到问题,具体可以参考 paramiko 文档:exit_status_ready

对于短时间运行的远程命令,等待 exit_status_code 的问题在于,你的本地线程可能会比你检查循环条件的速度更快地收到退出代码。在这种情况下,你将永远不会进入循环,readlines() 也不会被调用。这里有个例子:

# spawns new thread to communicate with remote
# executes whoami which exits pretty fast
stdin, stdout, stderr = ssh.exec_command("whoami") 
time.sleep(5)  # main thread waits 5 seconds
# command already finished, exit code already received
#  and set by the exec_command thread.
# therefore the loop condition is not met 
#  as exit_status_ready() already returns True 
#  (remember, remote command already exited and was handled by a different thread)
while not stdout.channel.exit_status_ready():
    if stdout.channel.recv_ready():
        stdoutLines = stdout.readlines()

在等待无限循环中 stdout.channel.recv_ready() 变为 True 之前,我怎么知道 stdout 上应该有数据?(如果没有预期的 stdout 输出,它不会变为 True)

channel.recv_ready() 只是表示缓冲区中有未读的数据。

def recv_ready(self):
    """
    Returns true if data is buffered and ready to be read from this
    channel.  A ``False`` result does not mean that the channel has closed;
    it means you may need to wait before more data arrives.

这意味着,由于网络问题(比如延迟的数据包、重传等)或者远程进程没有定期写入 stdout/stderr,可能会导致 recv_ready 返回 False。因此,把 recv_ready() 作为循环条件可能会导致你的代码过早返回,因为它有时会返回 True(当远程进程写入了 stdout,而你的本地通道线程接收到了这些输出)和有时返回 False(例如,远程进程在休眠,没有写入 stdout)。

此外,人们偶尔会遇到 paramiko 卡住的情况,这可能与 stdout/stderr 缓冲区满了 有关(可能与 Popen 和挂起进程的问题有关,当你从 stdout/stderr 中没有读取数据时,内部缓冲区会填满)。

下面的代码实现了一种分块读取 stdout/stderr 的解决方案,在通道打开时清空缓冲区。

def myexec(ssh, cmd, timeout, want_exitcode=False):
  # one channel per command
  stdin, stdout, stderr = ssh.exec_command(cmd) 
  # get the shared channel for stdout/stderr/stdin
  channel = stdout.channel

  # we do not need stdin.
  stdin.close()                 
  # indicate that we're not going to write to that channel anymore
  channel.shutdown_write()      

  # read stdout/stderr in order to prevent read block hangs
  stdout_chunks = []
  stdout_chunks.append(stdout.channel.recv(len(stdout.channel.in_buffer)))
  # chunked read to prevent stalls
  while not channel.closed or channel.recv_ready() or channel.recv_stderr_ready(): 
      # stop if channel was closed prematurely, and there is no data in the buffers.
      got_chunk = False
      readq, _, _ = select.select([stdout.channel], [], [], timeout)
      for c in readq:
          if c.recv_ready(): 
              stdout_chunks.append(stdout.channel.recv(len(c.in_buffer)))
              got_chunk = True
          if c.recv_stderr_ready(): 
              # make sure to read stderr to prevent stall    
              stderr.channel.recv_stderr(len(c.in_stderr_buffer))  
              got_chunk = True  
      '''
      1) make sure that there are at least 2 cycles with no data in the input buffers in order to not exit too early (i.e. cat on a >200k file).
      2) if no data arrived in the last loop, check if we already received the exit code
      3) check if input buffers are empty
      4) exit the loop
      '''
      if not got_chunk \
          and stdout.channel.exit_status_ready() \
          and not stderr.channel.recv_stderr_ready() \
          and not stdout.channel.recv_ready(): 
          # indicate that we're not going to read from this channel anymore
          stdout.channel.shutdown_read()  
          # close the channel
          stdout.channel.close()
          break    # exit as remote side is finished and our bufferes are empty

  # close all the pseudofiles
  stdout.close()
  stderr.close()

  if want_exitcode:
      # exit code is always ready at this point
      return (''.join(stdout_chunks), stdout.channel.recv_exit_status())
  return ''.join(stdout_chunks)

channel.closed 是通道提前关闭时的最终退出条件。在读取完一个数据块后,代码会检查是否已经收到退出状态,并且在此期间没有新的数据被缓冲。如果有新数据到达或者没有收到退出状态,代码将继续尝试读取数据块。一旦远程进程退出,并且缓冲区中没有新数据,我们就假设已经读取了所有内容,并开始关闭通道。请注意,如果你想接收退出状态,应该始终等到它被接收,否则 paramiko 可能会永远阻塞。

这样可以确保缓冲区不会填满,从而导致你的进程挂起。exec_command 只有在远程命令退出并且本地缓冲区没有剩余数据时才会返回。这个代码也更友好地使用了 select(),而不是在忙碌的循环中轮询,但对于短时间运行的命令可能会稍微慢一些。

仅供参考,为了防止一些无限循环,可以设置一个通道超时,当一段时间内没有数据到达时会触发。

 chan.settimeout(timeout)
 chan.exec_command(command)

撰写回答