【问题标题】:How to capture the output of executed command (python paramiko )?如何捕获执行命令的输出(python paramiko)?
【发布时间】:2018-01-28 11:27:13
【问题描述】:

我正在执行某些命令并希望捕获相同的输出。

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username="username",password="pwd")
stdin, stdout, stderr = ssh.exec_command("whoami")
out = stdout.read()
print out           # prints username
print stdout.read() # prints nothing, why is it so ?
                    # Instance #1

stdin, stdout, stderr = ssh.exec_command("kill -9 1111")
out = stdout.read()
print out #prints nothing. expected as it doesn't capture if it's successful
# print out # should print "-bash: kill: (1111) - No such process" , if it doesn't exist 
#--> Instance #2

在实例 #1 中,为什么打印 stdout.read() ,什么也不打印?

在实例 #2 中,如何捕获此类输出/响应?

【问题讨论】:

    标签: python-2.7 ssh stdout paramiko


    【解决方案1】:

    实例#1

    out = stdout.read()
    print stdout.read()
    

    第一个stdout.read() 已经消耗了所有的输出,所以第二个stdout.read() 什么也不返回。

    实例#2

    通常错误消息会打印到 stderr,因此您应该使用 stderr.read() 来获取错误。

    【讨论】:

      【解决方案2】:

      它可能什么也不打印,因为由于执行错误,stdout 是空的。 尝试打印 stderr 而不是 stdout

      【讨论】:

        猜你喜欢
        • 2017-02-26
        • 2012-06-29
        • 1970-01-01
        • 1970-01-01
        • 2020-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多