实验拓扑:
cloud连接本机,ip地址为192.168.56.1,五台交换机的配置的地址为192.168.1.201~205。现在通过paramiko,ssh进入五台设备,并且在五台设备上分别创建将192.168.56.0 0.0.0.255通告进入OSPF。
版本:python3.9
实验步骤:
一、ssh配置:
## 创建秘钥
[sw2]dsa local-key-pair create
## 配置SSH认证类型(密码/其他)
[sw2]ssh user prin authentication-type password
[sw2]ssh user prin service-type stelnet
[sw2]stelnet server enable
## 配置认证模式
[sw2]user-interface vty 0 4
[sw2-ui-vty0-4]authentication-mode aaa //配置认证模式
[sw2-ui-vty0-4]protocol inbound ssh //允许 ssh 连接虚拟终端
## 配置本地用户信息
[sw2]aaa
[sw2-aaa] local-user prin password cipher Huawei@123
[sw2-aaa]local-user prin privilege level 15
[sw2-aaa] local-user prin service-type ssh
二、paramiko脚本:
ssh_device.py: 使用paramiko连接设备
import time
import paramiko
def ssh_multicmd(ip, username, password, cmd_list, asy_id, wait_time=2, verbose=True):
try:
print('try ssh' + str(asy_id))
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, 22, username, password, timeout=5, compress=True)
print("You have successfully connect to " + ip + '\n')
except paramiko.ssh_exception.AuthenticationException:
print("User authentication failed for " + ip + ".")
return
# 激活交互式shell
command = ssh.invoke_shell()
# 等待网络设备回应
command.send("system\n")
# 执行具体的命令
for cmd in cmd_list:
command.send(cmd)
time.sleep(wait_time)
# 获取路由器返回信息
output = command.recv(65535)
x = output.decode('ascii')
# 关闭连接
ssh.close()
if verbose:
print(x)
return x
if __name__ == '__main__':
# 执行命令,查看show version的值,和配置OSPF
commands = ['ospf 1\n', 'area 0\n', 'network 192.168.56.0 0.0.0.255\n']
return_results = ssh_multicmd('192.168.56.205', 'prin', 'Huawei@123', commands, 1)
三、协程脚本与测试:
coroutine_ssh.py: 使用协程调用ssh_multicmd函数进行快速批量配置
from ssh_device import ssh_multicmd
import gevent
from gevent import monkey
monkey.patch_all()
commands = ['ospf 1\n', 'area 0\n', 'network 192.168.56.0 0.0.0.255\n']
def get_ssh_result(i):
print("start", i)
# 执行的任务函数
result = ssh_multicmd('192.168.56.20' + str(i), 'prin', 'Huawei@123', commands, i, verbose=False)
print("end", i)
return result
# 同时执行5个任务,id为1-5
tasks = [gevent.spawn(get_ssh_result, i) for i in [1, 2, 3, 4, 5]]
all_result = gevent.joinall(tasks)
# 获取执行信息
for x in all_result:
print(x.get())
协程测试结果: 可以看到,多个任务‘同时’执行,节约时间。
四、多进程/多线程脚本配置和测试
multiprocessing_ssh.py: 使用多进程或者多线程来配置脚本
from ssh_device import ssh_multicmd
from multiprocessing import cpu_count, Pool as ProcessPool
from multiprocessing.pool import ThreadPool
from multiprocessing import freeze_support
results = []
commands = ['ospf 1\n', 'area 0\n', 'network 192.168.56.0 0.0.0.255\n']
# 多进程
def multi_process(ip_prefix, suffix, username, password, commands):
freeze_support()
cpus = cpu_count() # 得到内核数的方法
pool = ProcessPool(cpus) # 有效控制并发进程或者线程数,默认为内核数(推荐)
# 设置对应函数和传入的参数
for i in suffix:
result = pool.apply_async(ssh_multicmd, args=(ip_prefix + str(i), username, password, commands, i, 2, False))
results.append(result)
# 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
pool.close()
pool.join()
for info in results:
print(info.get())
# 多线程
def multi_thread(ip_prefix, suffix, username, password, commands):
pool = ThreadPool(100)
# 设置对应函数和传入的参数
for i in suffix:
result = pool.apply_async(ssh_multicmd, args=(ip_prefix + str(i), username, password, commands, i, 2, False))
results.append(result)
# 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
pool.close()
pool.join()
for info in results:
print(info.get())
if __name__ == '__main__':
# 多线程
# multi_thread('192.168.56.20', range(1, 6), 'prin', 'Huawei@123', commands)
# 多进程
multi_process('192.168.56.20', range(1, 6), 'prin', 'Huawei@123', commands)
协程测试结果: 同样多个任务‘同时’进行,节约了时间。