Skip to main content
 首页 » 编程设计

Python SSH 没有给出完整的输出

2025年05月04日13fff_TT

我正在尝试编写一个脚本来登录远程机器,运行命令并返回输出。我正在使用 paramiko 库在 python 中执行此操作。但是,出于某种原因,没有生成完整的输出,只有一行。

为了隔离问题,我创建了一个名为 simple 的本地脚本,它运行命令并将输出发送到文件 remote_test_output.txt。然后我只是将文件 sftp 过来。该文件仅包含相同的一行。每次输出的唯一一行是相同的:命令的响应代码。

当我手动执行所有这些操作(ssh 结束、登录并运行 ./simple)时,它都按预期工作并且输出文件是正确的。但是,通过我机器上的脚本执行此操作时,它只返回单行。

我的代码:

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) 
ssh.connect(host, username, password) 
 
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('LD_LIBRARY_PATH=/opt/bin ./simple\n') 
 
print "output:", ssh_stdout.read()+"end" #Reading output of the executed command 
print "err:", ssh_stderr.read()#Reading the error stream of the executed command 
 
 
sftp = ssh.open_sftp() 
sftp.get('remote_test_output.txt', 'local_test_output.txt') 
sftp.close() 

返回的内容:

response code: 128 

应该返回什么:

field1:value1 
field2:value2 
response code: 128 
field3:value3 
field4:value4 
etc 

有没有人知道为什么我尝试调用的命令没有正常输出?

我必须包括 LD_LIBRARY_PATH 变量赋值,否则我会得到一个库不存在的错误。

请您参考如下方法:

根据 paramiko 的文档,“exec_command”方法返回一个 Channel 对象。第一个问题:您是否尝试将 bufsize 参数设置为一个? Channel 对象“表现得像一个套接字”。所以在文档中说:

http://www.facebook.com/photo.php?fbid=149324975212197&set=a.128010850676943.34896.126277080850320&type=1&ref=nf

这意味着 recv()(可能还有 read())只会读取读取缓冲区中的数据。因此,无论何时您的 read() 调用返回,并不意味着该进程已经在远程端执行。您应该使用 exit_status_ready() 方法来检查您的命令是否已执行:

http://www.lag.net/paramiko/docs/paramiko.Channel-class.html#exit_status_ready

只有在那之后你才能读取所有数据。好吧,这就是我的猜测。我可能是错的,但现在我无法检验我的理论。