Python-subprocess.Popen-ssh -t user @ host'service --status-all' [英] Python - subprocess.Popen - ssh -t user@host 'service --status-all'
问题描述
我已经阅读了很多示例,但是没有一个示例可以完成此特定任务.
I've read a bunch of examples but none of them work for this specific task.
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隧道检索远程命令的输出.
Why am i getting this error? Using os.popen(...) it works, it executes at least but i can't retrieve the output of the remote command via the SSH tunnel.
推荐答案
我认为您的命令列表有误:
I think your commands list is wrong:
commands = ['ssh', '-t', 'user@host', "service --status-all"]
x = Popen(commands, stdout=PIPE, stderr=PIPE)
此外,如果您要将列表传递给Popen
,我认为您不应该通过shell=True
.
Additionally, I don't think you should pass shell=True
if you're going to pass a list to Popen
.
例如要么这样做:
Popen('ls -l',shell=True)
或者这个:
Popen(['ls','-l'])
但不是这样:
Popen(['ls','-l'],shell=True)
最后,存在一个方便的功能,可用于将字符串拆分为列表的方式,就像您的shell一样:
Finally, there exists a convenience function for splitting a string into a list the same way your shell would:
import shlex
shlex.split("program -w ith -a 'quoted argument'")
将返回:
['program', '-w', 'ith', '-a', 'quoted argument']
这篇关于Python-subprocess.Popen-ssh -t user @ host'service --status-all'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!