我正在尝试制作一个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)
我很确定问题出在一些内部缓冲区的溢出上,但是哪一个以及如何修复它呢?你知道吗
非常感谢你给我的小费!你知道吗
我可以建议一种通过结构库通过ssh执行命令的不那么粗糙的方法。 它可能如下所示(省略ssh身份验证细节):
给定测试脚本
~/test.sh
所有输出都已正确使用
当
stdout.channel.exit_status_ready()
开始返回True
时,远程端可能仍有大量数据等待发送。但您只收到一个2048字节的块并退出。你知道吗不必检查退出状态,您可以继续调用
recv(2048)
,直到它返回一个空字符串which means,表示不再有数据出现:但实际上你可能只是想:
相关问题 更多 >
编程相关推荐