簡體   English   中英

通過SSH實時執行的流式python命令

[英]Streaming python command executed over ssh in real time

當ssh進入堡壘主機時,我正在另一台服務器上的ssh上執行一些python命令。 這些命令有時會花費很長時間,並且在執行完成之前,我看不到腳本在做什么或正在執行什么步驟,這可能會花費很長時間。 我想在腳本運行時在堡壘主機上查看腳本的日志和打印語句。

我當前的代碼正在使用subprocess.Popen 代碼的相關部分如下所示。 我聽說將-t標志添加到ssh命令與我的用例相關嗎?

def execute_command_over_ssh(host, command):
        process = subprocess.Popen(["ssh", host, command],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        if process.returncode != 0:
            print "There was an error executing the command ", command, " over ssh to host", host
            print stderr
            print stdout
            exit(1)
        else:
            return stdout

我正在通過調用以下命令執行一系列不同的命令

execute_command_over_ssh()

方法,直到整個腳本執行完畢,我看不到每個命令的最終輸出。

這將把stderr流重定向到stdout,並在生成時返回ssh的stdout。

import subprocess
import logging

logger = logging.basicConfig(level=logging.DEBUG)

if __name__ == '__main__':
    p = subprocess.Popen('ssh user@ip', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while p.poll() is None:
        for line in p.stdout:
            line = line.decode().strip('\n')
            logging.debug(line)

輸出:

DEBUG:root:Pseudo-terminal will not be allocated because stdin is not a terminal.
DEBUG:root:Authenticated to x.x.x.x.
DEBUG:root:Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-51-generic x86_64)
DEBUG:root:
DEBUG:root:* Documentation:  https://help.ubuntu.com
DEBUG:root:* Management:     https://landscape.canonical.com
DEBUG:root:* Support:        https://ubuntu.com/advantage
...
...

暫無
暫無

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

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