【发布时间】:2013-01-02 16:54:47
【问题描述】:
我已经阅读了很多示例,但没有一个适用于此特定任务。
Python 代码:
x = Popen(commands, stdout=PIPE, stderr=PIPE, shell=True)
print commands
stdout = x.stdout.read()
stderr = x.stderr.read()
print stdout, stderr
return stdout
输出:
[user@host]$ python helpers.py
['ssh', '-t', 'user@host', ' ', "'service --status-all'"]
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
[-D [bind_address:]port] [-e escape_char] [-F configfile]
[-I pkcs11] [-i identity_file]
[-L [bind_address:]port:host:hostport]
[-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
[-R [bind_address:]port:host:hostport] [-S ctl_path]
[-W host:port] [-w local_tun[:remote_tun]]
[user@]hostname [command]
为什么会出现这个错误? 使用 os.popen(...) 它可以工作,它至少可以执行,但我无法通过 SSH 隧道检索远程命令的输出。
【问题讨论】:
-
输出表明您没有向命令传递足够/正确的参数。
-
去掉空格项,去掉最后一个参数两边的单引号。
-
顺便说一句,您是否使用公钥身份验证?还是密码认证?
-
考虑使用
paramiko/fabric。 -
不相关:使用
stdout, stderr = x.communicate()而不是stdout = x.stdout.read(); stderr = x.stderr.read()。如果commands产生足够的输出,后者可能会导致死锁。另一种方法是使用不同的线程同时读取标准输出/标准错误或使用select或fnctl模块(Unix)
标签: python linux ssh subprocess popen