首页 > 解决方案 > 在 Paramiko 中使用 exec_command 实时输出 wget 命令

问题描述

我正在尝试在所有机器上下载一个文件,因此我创建了一个 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())

下载完成后将打印输出。!

有没有办法可以实时打印输出?

编辑:我看过这个答案并应用了这样的东西:

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命令,它不起作用..

标签: pythonparamiko

解决方案


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

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


推荐阅读