【问题标题】:Using Python to ssh then run bash script. The output of the running bash script i need to display on the screen使用 Python ssh 然后运行 ​​bash 脚本。我需要在屏幕上显示的正在运行的 bash 脚本的输出
【发布时间】:2019-02-08 22:06:18
【问题描述】:

我正在使用 Python(OSX Python 2.7.10)通过 ssh 进入 Debian 机器(Python 2.7.9),然后运行 ​​bash 脚本(./capture)。 bash 脚本包含一些 tcpdump 命令。我无法弄清楚的问题是如何在终端上显示正在运行的 bash 脚本的实时结果。

#!/usr/bin/env python3
import subprocess, os
output = subprocess.run(["ssh", "ju@192.168.199.125", "sudo ./capture"])
print(output)

我能够 ssh 并成功运行脚本,但我没有得到任何输出。当我按 CTRL C 时,我得到以下跟踪:

**^CTraceback (most recent call last):
  File "/Users/junesjoseph/run.py", line 3, in <module>
    output = subprocess.run(["ssh", "junes@192.168.199.125", "sudo ./capture"])
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 405, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 835, in communicate
    self.wait()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1457, in wait
    (pid, sts) = self._try_wait(0)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1404, in _try_wait
    (pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt**

非常感谢任何帮助。谢谢

【问题讨论】:

    标签: python bash ssh subprocess


    【解决方案1】:

    subprocess.run 返回的对象是一个CompletedProcess 对象,其属性包含已完成进程的stdoutstderr。您不想直接打印它,但您可以使用它来获取您要打印的属性。

    import subprocess  # no reason to import os
    subssh = subprocess.run(["ssh", "ju@192.168.199.125", "sudo ./capture"],
        # Set up for capturing stdout and stderr
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        # Add commonly useful attributes
        check=True, universal_newlines=True)
    print(subssh.output)
    

    如果您真的只想将输出显示在标准输出上,那么捕获它以便打印它基本上是多余的。只需将其设置为直接显示,只需不将stdoutstderr 设置为任何内容:

    subssh = subprocess.run(["ssh", "ju@192.168.199.125", "sudo ./capture"],
        # Don't set up for capturing -- leave stdout and stderr alone
        check=True, universal_newlines=True)
    

    也许另请参阅Running Bash commands in Python,我在其中发布了有关subprocess 常见问题的更详细答案。

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2016-03-01
      • 2018-04-17
      • 1970-01-01
      • 2018-07-05
      • 2022-01-05
      相关资源
      最近更新 更多