简体   繁体   English

通过SSH实时执行的流式python命令

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

While ssh'ed into a bastion host, I'm executing some python commands over ssh on another server. 当ssh进入堡垒主机时,我正在另一台服务器上的ssh上执行一些python命令。 These commands sometimes take a long time, and I can't see what the script is doing or what step it's on until it finishes executing, which can take a long time. 这些命令有时会花费很长时间,并且在执行完成之前,我看不到脚本在做什么或正在执行什么步骤,这可能会花费很长时间。 I would like to view the logs and print statements of the script on the bastion host as the script is running. 我想在脚本运行时在堡垒主机上查看脚本的日志和打印语句。

My current code is using subprocess.Popen . 我当前的代码正在使用subprocess.Popen The relevant parts of the code are shown below. 代码的相关部分如下所示。 I've heard that adding the -t flag to the ssh command is relevant for my use case? 我听说将-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

I'm executing a chain of different commands by calling the 我正在通过调用以下命令执行一系列不同的命令

execute_command_over_ssh()

method and I don't see the final output of every command until the entire script has finished executing. 方法,直到整个脚本执行完毕,我看不到每个命令的最终输出。

This one will redirect stderr stream into stdout and will return you the stdout of ssh as it's produced. 这将把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)

output: 输出:

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