这是我定义的一个ssh登陆并使用命令获取执行结果的一个函数,现在使用的是time.sleep() 来保证命令能够执行完成。这样就导致我批量执行的速度就比较慢,请问可否有不使用time.sleep() 方法,使用循环来判断我的命令已执行完成。然后将结果输出到output。
不要使用exec_command方法,这个一次只能执行一条命令。
import paramiko
import time
device_ip = '1.1.1.1'
username = 'luotao'
password = 'luotao'
command1 = 'terminal length 0'
command2 = 'show run'
command3 = 'show tech'
def ssh_exec_command2(device_ip, username, password, command1, command2):
port = 22
ssh_client = paramiko.SSHClient()
ssh_client.load_system_host_keys()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(device_ip, port, username, password, timeout=5)
print('连接设备 ', device_ip)
command = ssh_client.invoke_shell()
command.send(command1+'\n')
time.sleep(1)
command.send(command2+'\n')
time.sleep(50)
command.send(command3+'\n')
time.sleep(50)
output = command.recv(999999)
ssh_client.close()
return output
```
本来写了一些思路,但是突然意识到,你要操作的设备可能不是主流linux,对一些命令、语法支持可能不足
那么我们就从SSH协议上找到突破口
重点:命令执行完之后执行一次exit
这样,ssh断开这意味着所有命令执行完毕
,如果多个ssh主机批量执行的话,可以通过多线程或者多进行处理,建立多个SSH会话
代码示例:
def ssh_exec_command2(device_ip, username, password, command1, command2):
port = 22
ssh_client = paramiko.SSHClient()
ssh_client.load_system_host_keys()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(device_ip, port, username, password, timeout=5)
print("连接设备 ", device_ip)
channel = ssh_client.invoke_shell()
stdin = channel.makefile("wb")
stdout = channel.makefile("rb")
stdin.write(
f"""
{command1}
{command2}
exit
"""
)
print("执行完毕")
output = stdout.read()
print("读取完毕")
ssh_client.close()
return output
https://blog.csdn.net/qq_29778641/article/details/82186438 https://blog.csdn.net/qq_29778641/article/details/82186438
循环来取 命令执行后的结果。
python的函数大部分是同步的,应该不需要sleep
我建议把下面用Channel来执行command改为用clinet执行command
command = ssh_client.invoke_shell()
command.send(command1+'\n')
time.sleep(1)
command.send(command2+'\n')
time.sleep(50)
command.send(command3+'\n')
变成
stdin, stdout, stderr = ssh_client.exec_command(command1+'&'+command2+'&'+command3)
stdout.channel.set_combine_stderr(True)
output = stdout.readlines()
可以试试subprocess 库,换种思路:
给定超时时间,超时时间内完成,return返回正确的值,超时时间内未完成,终止进程
https://www.runoob.com/w3cnote/python3-subprocess.html https://www.runoob.com/w3cnote/python3-subprocess.html