在 Paramiko 中使用 exec_command 实时输出 wget 命令

Real time output of wget command by using exec_command in Paramiko

我试图在所有机器上下载一个文件,因此我创建了一个 python 脚本。它使用模块 paramiko

只是代码的一个片段:

from paramiko import SSHClient, AutoAddPolicy
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect(args.ip,username=args.username,password=args.password)

stdin, stdout, stderr = ssh.exec_command("wget xyz")
print(stdout.read())

下载完成后将打印输出!

有什么方法可以实时打印输出吗?

编辑:我查看了 this 答案并应用了如下内容:

def line_buffered(f):
    line_buf = ""
    print "start"
    print f.channel.exit_status_ready()
    while not f.channel.exit_status_ready():
        print("ok")
        line_buf += f.read(size=1)
        if line_buf.endswith('\n'):
            yield line_buf
            line_buf = ''

 in, out, err = ssh.exec_command("wget xyz")
 for l in line_buffered(out):
        print l

但是,它不是实时打印数据。!它等待文件下载,然后打印整个下载状态。

另外,我试过这个命令:echo one && sleep 5 && echo two && sleep 5 && echo three 并且输出是实时的 line_buffered 函数。但是,对于 wget 命令,它不起作用..

wget的进度信息输出到stderr所以你应该写line_buffered(err).

或者您可以使用 exec_command("wget xyz", get_pty=True),它将结合 stdoutstderr