簡體   English   中英

使用Python ssh然后運行bash腳本。 我需要在屏幕上顯示正在運行的bash腳本的輸出

[英]Using Python to ssh then run bash script. The output of the running bash script i need to display on the screen

我正在使用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 CI時,得到以下跟蹤:

**^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**

任何幫助是極大的贊賞。 謝謝

subprocess.run返回的對象是CompletedProcess對象, 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)

也許也可以參閱《 在Python運行Bash命令》,其中我已經發布了有關subprocess常見問題的更詳細的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM