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

时间:2018-07-12 10:01:09

标签: python 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命令,它不起作用。.

1 个答案:

答案 0 :(得分:1)

wget的进度信息输出到 stderr ,因此您应该编写line_buffered(err)

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