我正在尝试使用Paramiko执行备份。进行备份时,我让脚本休眠240秒钟以希望它完成,但是有时这可能需要更长的时间。无论如何,我可以使用循环每20秒检查一次,以查看输出变量是否存在诸如“ backup complete”之类的关键字。
import datetime, time
from time import sleep
from Tkinter import *
import paramiko
from paramiko_expect import SSHClientInteraction
def backup():
prompt = 'root@servername user'
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=server, username=user, password=pass)
interact = SSHClientInteraction(client, timeout=10, display=True)
except paramiko.AuthenticationException:
print("Authentication failed, please verify your credentials: %s")
except paramiko.SSHException as sshException:
print("Unable to establish SSH connection: %s" % sshException)
except paramiko.BadHostKeyException as badHostKeyException:
print("Unable to verify server's host key: %s" % badHostKeyException)
except Exception as e:
print(e.args)
interact.send('su')
interact.expect("Password:")
interact.send("supassword")
interact.expect(prompt)
interact.send("who")
interact.expect(prompt)
cmd_output_who = interact.current_output_clean
print cmd_output_who
答案 0 :(得分:0)
SSHClient.invoke_shell
用于实现交互式终端会话(例如,如果您正在实现自己的SSH终端客户端),而不是用于自动执行命令。终端是一个带有输入和输出的黑匣子。它没有任何API可以执行命令并等待命令完成。
使用SSHClient.exec_command
执行命令,使用Channel.recv_exit_status
或Channel.exit_status_ready
等待命令完成。
参见Wait until task is completed on Remote Machine through Python。