Python-subprocess.Popen-ssh-t user@host“服务——全部状态”

2024-05-15 05:44:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过很多例子,但没有一个能完成这个特定的任务。

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隧道检索远程命令的输出。


Tags: hostreadbindportaddressstderrstdoutssh
1条回答
网友
1楼 · 发布于 2024-05-15 05:44:27

我认为你的命令列表是错误的:

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

另外,如果要将列表传递给Popen,我认为不应该传递shell=True

例如,执行以下任一操作:

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

或者这个:

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

但不是这个:

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

最后,还有一个方便的函数,可以像shell一样将字符串拆分为列表:

import shlex
shlex.split("program -w ith -a 'quoted argument'")

将返回:

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

相关问题 更多 >

    热门问题