在python中丢失stdout数据

2024-05-16 11:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个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)                                                                                    

我很确定问题出在一些内部缓冲区的溢出上,但是哪一个以及如何修复它呢?你知道吗

非常感谢你给我的小费!你知道吗


Tags: importip脚本bashparamikooutputportstdout
2条回答

我可以建议一种通过结构库通过ssh执行命令的不那么粗糙的方法。 它可能如下所示(省略ssh身份验证细节):

from fabric import Connection

with Connection('user@localhost') as con:
    res = con.run('~/test.sh', hide=True)
    lines = res.stdout.split('\n')
    print('{} lines readen.'.format(len(lines)))

给定测试脚本~/test.sh

#!/bin/sh
for i in {1..1234}
do
  echo "Line $i"
done

所有输出都已正确使用

stdout.channel.exit_status_ready()开始返回True时,远程端可能仍有大量数据等待发送。但您只收到一个2048字节的块并退出。你知道吗

不必检查退出状态,您可以继续调用recv(2048),直到它返回一个空字符串which means,表示不再有数据出现:

output = ''
next_chunk = True
while next_chunk:
    next_chunk = stdout.channel.recv(2048)
    output += next_chunk

但实际上你可能只是想:

output = stdout.read()

相关问题 更多 >