Skip to main content
 首页 » 编程设计

python之如何使用 Paramiko 从远程机器上执行的命令中获取 stderr 返回值

2025年02月15日13kevingrace

请检查下面的代码(我认为这是不言自明的)。

代码:

import sys 
import paramiko 
 
def execute_command_on_remote_machine(ip_addr, command): 
    try: 
        client = paramiko.SSHClient() 
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
 
        client.connect(str(ip_addr), username='root', password='****') 
        chan = client.get_transport().open_session() 
        #chan.get_pty() 
 
        stdin, stderr, stdout = [], [], [] 
        stdin, stdout, stderr = client.exec_command(command, get_pty=True) 
 
        err_list = [line for line in stderr.read().splitlines()] 
        out_list = [line for line in stdout.read().splitlines()] 
 
        client.close() 
        return out_list, err_list 
    except Exception, e: 
        print str(e) 
        sys.exit(1) 
 
 
output, error = execute_command_on_remote_machine("*.*.*.*", "dinesh") 
 
print "Output is - ",output 
print "Error is - ",error 

输出:

D:\dsp_jetbrains\AWS_Persistence>python chk.py 
Output is -  ['bash: dinesh: command not found'] 
Error is -  [] 

问题:

作为输入,我传递了一个不正确的命令,我预计“dinesh:command not found”将打印为“Error is”。但是,它带有“Output is”。

问题:

paramiko 中 exec_command 的输出和错误如何工作?

附加测试用例:

我还尝试使用存在的命令,但向该命令传递了错误的输入。示例 - lsof -f dinesh

但结果是一样的。

D:\dsp_jetbrains\AWS_Persistence>python chk.py 
Output is -  ['lsof: unknown file struct option: d', 'lsof: unknown file struct 
option: i', 'lsof: unknown file struct option: n', 'lsof: unknown file struct op 
tion: e', 'lsof: unknown file struct option: s', 'lsof: unknown file struct opti 
on: h', 'lsof 4.87', ' latest revision: ftp://lsof.itap.purdue.edu/pub/tools/uni 
x/lsof/', ' latest FAQ: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/FAQ', ' l 
atest man page: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/lsof_man', ' usag 
e: [-?abhKlnNoOPRtUvVX] [+|-c c] [+|-d s] [+D D] [+|-f[gG]] [+|-e s]', ' [-F [f] 
] [-g [s]] [-i [i]] [+|-L [l]] [+m [m]] [+|-M] [-o [o]] [-p s]', '[+|-r [t]] [-s 
 [p:s]] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [-Z [Z]] [--] [names]', "Use t 
he ``-h'' option to get more help information."] 
Error is -  [] 

请您参考如下方法:

你可能不应该使用 get_pty 除非你知道你需要它。考虑删除:

chan.get_pty() 

和改变:

stdin, stdout, stderr = client.exec_command(command, get_pty=True) 

到:

stdin, stdout, stderr = client.exec_command(command) 

来自DOCS :

Request a pseudo-terminal from the server. This is usually used right after creating a client channel, to ask the server to provide some basic terminal semantics for a shell invoked with invoke_shell. It isn’t necessary (or desirable) to call this method if you’re going to exectue a single command with exec_command.

A pseudo-terminal如果您希望您的 ssh 连接看起来像用户已连接,则使用它。很少需要这个。一个人为的例子是,如果您想通过发送和接收 ansi 终端序列在远端使用 VIM。

如果没有 get_pty,远程执行的命令将简单地连接 stdin/stdout/stderr 三重奏,就像在管道中一样。

很少需要 get_pty 可能是它不是默认设置的原因。