如何通过Paramiko获取广播信息

How to get the broadcast messages via Paramiko

我正在尝试通过 paramiko 获取广播消息以确保操作已完全执行。像这样。

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, 22, user, passwd, timeout=180)
command = 'sleep 3; wall "The system will shutdown in 3 seconds."; sudo nohup shutdown -h now;'
stdin, stdout, stderr = ssh.exec_command(command, timeout=300)
if "The system will shutdown in 3 seconds." in stdout.read().encode('utf-8'):
    print "Command success!!"
else
    print "Command failure!!"

但是,我总是得到一个空输出。我怎样才能得到输出?

广播消息仅发送到交互式会话。

所以你至少需要将SSHClient.exec_commandget_pty参数设置为True

也许您甚至需要通过 SSHClient.invoke_shell 使用 shell 频道。


虽然其实我不明白你为什么要抓广播。那 "ensure" 是什么意思?也许像检查 wall 退出代码这样的方法可能是更可靠的方法。