是否可以通过Paramiko登录和注销远程/ SSH会话,并在每次登录/登录时执行不同的命令?
我能够SSH到路由器并执行命令,但是事实证明,我可以在单个会话中多次运行该命令;但是,我想在每次执行命令时登录并注销
def run_ssh_command(username, password, ip_add):
"""
Using paramiko to SSH into remote locations and run commands
"""
port = 22
remote_connection = paramiko.SSHClient()
remote_connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = ["192.168.122.164", "192.168.122.228"]
for ip_add in host:
while True:
try:
remote_connection.connect(ip_add, port, username, password, look_for_keys=False, timeout=5.0)
except paramiko.SSHException:
print('SSH error')
remote_connection.close()
except paramiko.AuthenticationException:
print('Authentication failed')
remote_connection.close()
except socket.timeout:
print('Socket timeout')
remote_connection.close()
except socket.error:
print('Socket error')
stdin, stdout, stderr = remote_connection.exec_command("show ip bgp summary")
output = stdout.readlines() # prints output in list format
iterator = range(len(output))
while True:
for i in iterator:
if 'Idle' in output[i].split() or 'Active' in output[i].split():
print('BGP not reconverged')
break
else:
print('BGP OK')
break
break
if __name__ == '__main__':
while True:
run_ssh_command("julls", "cisco", "ip_add")
break
理想情况下,我想在遇到“ BGP未重新融合”时立即爆发;建立另一个会话,检查“ BGP OK”是否正确,如果注销,然后执行另一个“ remote_connection.exec_command”-在这种情况下,我将发出“重新加载”之类的信息,而不是“ show ip bgp summary”。 paramiko可以做到这一点吗,还是我需要一个单独的模块?