gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:29 25 4
gpt4 key购买 nike

我已经阅读了很多示例,但没有一个适用于此特定任务。

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

最佳答案

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

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

关于Python - subprocess.Popen - ssh -t user@host 'service --status-all',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com