繁体   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