通常情况下,我们登录网络设备进行配置下发,都是使用paramiko或者netmiko,但是这两种方法由于存在大量的IO等待,效率比较低,可以使用netdevice模块的异步进程,来提升效率。
,例如获取一个设备的接口IP地址为例子,使用netmiko实现:
import time
from netmiko import ConnectHandler
def get_ip():
net_connect = ConnectHandler(device_type='hp_comware', host='10.0.49.51', username='3210', password='!QAZ2wsx!12')
commands = 'dis cu int l0'
out=net_connect.send_command(commands).splitlines()
ip_addr = out[2].split()[2]
print(ip_addr)
return ip_addr
start_time = time.time()
get_ip()
print('Time elapsed: %.2f' % (time.time() - start_time))
输出:
1.1.1.1
Time elapsed: 4.45
使用netdevice实现
import netdev
import asyncio
import time
async def get_ip(dev):
async with netdev.create(**dev) as ios:
commands = 'dis cu int l0'
out = await ios.send_command(commands)
out=out.splitlines()
ip_addr=out[2].split()[2]
return ip_addr
async def run():
dev1 = {'username': '3210',
'password': '!QAZ2wsx!12', # 填写你的交换机密码
'device_type': 'hp_comware', # 华为 华三测试用这个type,因为没有huawei huasan关键字的type,netdev目前2020年仅支持它罗列的操作系统
'host': '10.0.49.51'
}
ip_addr = await get_ip(dev1)
print(ip_addr)
start_time = time.time()
asyncio.run(run())
print('Time elapsed: %.2f' % (time.time() - start_time))
结果输出:
1.1.1.1
Time elapsed: 0.14
速度快了30多倍哦,嗨用什么paramiko和netmiko哈