Python - subprocess.Popen - ssh -t user@host 'service --status-all'

不羁的心 提交于 2020-02-24 20:57:48

问题


I've read a bunch of examples but none of them work for this specific task.

Python code:

x = Popen(commands, stdout=PIPE, stderr=PIPE, shell=True)
print commands
stdout = x.stdout.read()
stderr = x.stderr.read()
print stdout, stderr
return stdout

Output:

[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]

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.


回答1:


I think your commands list is wrong:

commands = ['ssh', '-t', 'user@host', "service --status-all"]
x = Popen(commands, stdout=PIPE, stderr=PIPE)

Additionally, I don't think you should pass shell=True if you're going to pass a list to Popen.

e.g. either do this:

Popen('ls -l',shell=True)

or this:

Popen(['ls','-l'])

but not this:

Popen(['ls','-l'],shell=True)

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'")

will return:

['program', '-w', 'ith', '-a', 'quoted argument']


来源:https://stackoverflow.com/questions/14408094/python-subprocess-popen-ssh-t-userhost-service-status-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!