如何捕获执行命令的输出(python paramiko)?
How to capture the output of executed command (python paramiko )?
我正在执行某些命令并希望捕获相同的输出。
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 中,如何捕获这样的 outputs/response ?
实例 #1
out = stdout.read()
print stdout.read()
第一个 stdout.read()
已经消耗了所有输出,所以第二个 stdout.read()
returns 什么都没有。
实例 #2
通常错误消息会打印到 stderr 所以你应该使用 stderr.read()
来获取错误。
它可能什么都不打印,因为执行错误导致标准输出为空。
尝试打印 stderr 而不是 stdout
我正在执行某些命令并希望捕获相同的输出。
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 中,如何捕获这样的 outputs/response ?
实例 #1
out = stdout.read()
print stdout.read()
第一个 stdout.read()
已经消耗了所有输出,所以第二个 stdout.read()
returns 什么都没有。
实例 #2
通常错误消息会打印到 stderr 所以你应该使用 stderr.read()
来获取错误。
它可能什么都不打印,因为执行错误导致标准输出为空。 尝试打印 stderr 而不是 stdout