Tor*_*xed 1 python linux ssh subprocess popen
我已经阅读了一些示例,但它们都不适用于此特定任务.
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
Run Code Online (Sandbox Code Playgroud)
输出:
[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]
Run Code Online (Sandbox Code Playgroud)
为什么我会收到此错误?使用os.popen(...)它起作用,它至少执行但我无法通过SSH隧道检索远程命令的输出.
我认为你的命令列表是错误的:
commands = ['ssh', '-t', 'user@host', "service --status-all"]
x = Popen(commands, stdout=PIPE, stderr=PIPE)
Run Code Online (Sandbox Code Playgroud)
另外,shell=True如果您要将列表传递给我,我认为您不应该通过Popen.
例如,要么这样做:
Popen('ls -l',shell=True)
Run Code Online (Sandbox Code Playgroud)
或这个:
Popen(['ls','-l'])
Run Code Online (Sandbox Code Playgroud)
但不是这个:
Popen(['ls','-l'],shell=True)
Run Code Online (Sandbox Code Playgroud)
最后,存在一个便利函数,用于将字符串拆分为一个列表,就像shell一样:
import shlex
shlex.split("program -w ith -a 'quoted argument'")
Run Code Online (Sandbox Code Playgroud)
将返回:
['program', '-w', 'ith', '-a', 'quoted argument']
Run Code Online (Sandbox Code Playgroud)