在python中丢失标准输出数据
我正在尝试制作一个python脚本,它将通过ssh在远程机器上运行一个bash脚本,然后解析其输出。bash脚本在stdout中输出大量数据(比如5兆字节的文本/50k行),这是一个问题——我只在大约10%的情况下获得所有数据。在其他90%的情况下,我得到了我期望的97%,看起来它总是在最后修剪。我的脚本是这样的:在python中丢失标准输出数据,python,linux,bash,ssh,Python,Linux,Bash,Ssh,我正在尝试制作一个python脚本,它将通过ssh在远程机器上运行一个bash脚本,然后解析其输出。bash脚本在stdout中输出大量数据(比如5兆字节的文本/50k行),这是一个问题——我只在大约10%的情况下获得所有数据。在其他90%的情况下,我得到了我期望的97%,看起来它总是在最后修剪。我的脚本是这样的: import subprocess import re import sys import paramiko def run_ssh_command(ip, port, usern
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)
我很确定问题出在一些内部缓冲区溢出,但哪一个以及如何修复它
非常感谢你给我的小费 我可以推荐一种通过结构库通过ssh执行命令的不太粗糙的方法。 它可能如下所示(省略ssh身份验证详细信息): 给定测试脚本
~/test.sh
#!/bin/sh
for i in {1..1234}
do
echo "Line $i"
done
当
stdout.channel.exit_status_ready()
开始返回True
时,所有输出都已正确使用,远程端可能仍有大量数据等待发送。但您只收到2048字节中的一个块并退出
不必检查退出状态,您可以继续调用recv(2048)
,直到它返回一个空字符串,表示不再有数据出现:
output = ''
next_chunk = True
while next_chunk:
next_chunk = stdout.channel.recv(2048)
output += next_chunk
但实际上,你可能只是想:
output = stdout.read()
output = stdout.read()