我正在尝试制作一个 python 脚本,该脚本将通过 ssh 在远程计算机上运行 bash 脚本,然后解析其输出。 bash 脚本在 stdout 中输出大量数据(如 5 兆字节的文本/50k 行),这是一个问题——我只在大约 10% 的情况下获取所有数据。在其他 90% 的情况下,我得到了我预期的大约 97%,而且它看起来总是在最后修剪。这是我的脚本的样子:
import subprocess
import re
import sys
import paramiko
def run_ssh_command(ip, port, username, password, command):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)
stdin, stdout, stderr = ssh.exec_command(command)
output = ''
while not stdout.channel.exit_status_ready():
solo_line = ''
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
solo_line = stdout.channel.recv(2048).
output += solo_line
ssh.close()
return output
result = run_ssh_command(server_ip, server_port, login, password, 'cat /var/log/somefile')
print "result size: ", len(result)
我很确定问题出在某些内部缓冲区溢出,但到底是哪一个以及如何修复它?
非常感谢您的任何提示!
最佳答案
当 stdout.channel.exit_status_ready()
开始返回 True
时,远端可能仍有大量数据等待发送。但是您只收到了一个 2048 字节的 block 并退出。
您可以继续调用 recv(2048)
,而不是检查退出状态,直到它返回一个空字符串 which means没有更多的数据来了:
output = ''
next_chunk = True
while next_chunk:
next_chunk = stdout.channel.recv(2048)
output += next_chunk
但实际上你可能只是想要:
output = stdout.read()
关于python - 在 python 中丢失标准输出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50284343/