python - 在 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
命令,它不起作用..
解决方案
wget
的进度信息输出到stderr所以你应该写line_buffered(err)
.
或者您可以使用exec_command("wget xyz", get_pty=True)
结合stdout和stderr。
推荐阅读
- memory - Kubectl 命令随机响应缓慢
- python - 创建一个匹配多于两列的成对数据框
- java - 如何将 Kafka 配置为像 FiFo 队列一样工作?
- .net-core - 是否有本地方法来重新处理对提示的响应?
- sql - 选择转换为 xml 的行
- excel-formula - 单元格格式是否可以对单元格内容执行公式?
- scala - 如何使用akka类型在akka流中使用ActorSink.actorRefWithBackpressure
- android - 嵌套在我的抽屉导航器中的重置堆栈
- javascript - AssertionError:无法比较节点 js 中的两个对象
- django - .objects.filter(name__containe=data) 的返回结果格式,不带引号