【问题标题】:subprocess python multiple commands子进程python多个命令
【发布时间】:2020-11-26 18:22:50
【问题描述】:

想要打开一个 ssh 会话,运行命令并在进程运行时实时获取输出(此基础将涉及在远程服务器上运行其他命令)

from subprocess import Popen, PIPE

with Popen(['ssh <server-domain-name>',
            ],shell=True,
           stdin=PIPE, stdout=PIPE, stderr=PIPE,
           universal_newlines=True) as ssh:
    output1 = ssh.stdin.write('ls -l')
    output2 = ssh.stdin.write('mkdir test')
    status = ssh.poll()

print(output1)
print(output2)

到目前为止,这就是我所拥有的,使用ssh.communicate[&lt;command&gt;] 给出了正确的输出,但在第一个命令之后关闭了子进程,有什么想法吗?

【问题讨论】:

  • 你确定标准输入应该是一个管道吗?
  • 在这里使用 shell=True 是错误的,但恰好在 Windows 上工作。不过,您真的想尽可能避免使用shell=True。见Actual meaning of shell=True in subprocess;在这种情况下,请尝试 Popen('ssh', server], ...),但正如您所发现的,您确实需要像 Paramiko 或 Expect 这样的高级库来与远程服务器上的交互式进程对话。

标签: python ssh subprocess


【解决方案1】:

为我工作

from fabric2 import Connection
with Connection('<host>') as c:
    print(CGREEN +'connected succsfully!' + CEND)

    #gather user info
    user = io.StringIO
    user = c.run("whoami", hide=True)
    print(f'user found:{user.stdout} ')

    #fetching files
    c.run(<command>, pty=True)

【讨论】:

    猜你喜欢
    • 2017-08-28
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2017-01-09
    • 2012-10-31
    相关资源
    最近更新 更多