【问题标题】:why paramiko ssh can't output the print info in realtime为什么 paramiko ssh 不能实时输出打印信息
【发布时间】:2017-09-05 20:29:25
【问题描述】:

我使用python3 ssh,现在我可以登录远程设备,并执行我的远程C程序,但程序打印信息无法实时显示在本地电脑上。如果我的 C 程序使用setbuf(stdout, NULL); 设置非缓冲,我的 PC 可以获得实时信息;我想知道如果C程序没有设置非缓冲,如何在本地PC上获取远程实时信息。

这是我的代码:

def get_ssh_log(hostip, login_name, pw, privaete_key, cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='%s' % hostip, port=22, username='%s' % login_name, password='%s' % pw,key_filename='%s' % privaete_key)
    stdin, stdout, stderr = ssh.exec_command("%s" % cmd, bufsize=1)
    for line in iter(stdout.readline, ""):
        print(line)
    ssh.close()

【问题讨论】:

  • 你知道"%s" % cmd 就是cmd 对吧?
  • 我猜@JohnZwinck 的评论也适用于该函数中% 运算符的所有其他用途。
  • @JohnZwinck 是的,我知道 "%s" % cmd 只是 cmd;

标签: python python-3.x ssh


【解决方案1】:

您可以在 expect 包中的包装器 unbuffer 下运行任何程序。在你的情况下:

ssh.exec_command("unbuffer %s" % cmd)

当然,这假设unbuffer 已安装在目标机器上。

参考:https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe

【讨论】:

  • 远程设备是嵌入式设备,运行openwrt os,不方便安装任何包。如果本地PC中的python3有其他方法可以实时获取输出。谢谢。
  • @simon:那么你可以自己实现 unbuffer 程序,也许在 Python 中,并在执行前使用 SFTP 将其复制到目标。此类程序的源代码在这里:man7.org/tlpi/code/online/dist/pty/unbuffer.c.html
猜你喜欢
  • 1970-01-01
  • 2021-04-08
  • 2021-11-25
  • 1970-01-01
  • 2016-10-17
  • 2016-03-10
  • 2023-01-11
  • 2015-02-23
  • 2020-11-09
相关资源
最近更新 更多