【问题标题】:Python SSH not giving full outputPython SSH没有给出完整的输出
【发布时间】:2012-09-28 17:08:51
【问题描述】:

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

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

当我手动完成所有这些操作(ssh over、登录并运行 ./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 变量分配,否则我会收到库不存在错误。

【问题讨论】:

  • 也许某处的重定向不完整?你试过2>&1吗? ./simple 在做什么,./simple 运行的基本命令是什么?
  • @Dubslow 这是一个获取状态命令。它获取另一台机器的状态、温度等。我知道重定向不是问题,因为如果我 ssh 并通过终端运行它,它可以正常工作

标签: python ssh paramiko


【解决方案1】:

根据 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 2022-01-03
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多