我基于知乎作者 九净 的文章学习了netmiko的基本使用方法,便自己搭一个简单的环境练习一下,完成多设备的配置下发和备份
一、实验环境
以本环境为例:在自己主机的192.168.0.100网卡上配置网关192.168.0.1,不然没有回程路由;另外需要断开网络连接,确保本机默认路由只有一条去往192.168.0.1的路由
ssh配置:
stelnet server enable
user-interface vty 0 4
protocol inbound all
authentication-mode aaa
aaa
local-user netdevops password cipher 123
local-user netdevops privilege level 15
local-user netdevops service-type ssh
使用远程连接确认配置无误
二、代码及效果
# 通过netmiko模块的链接库函数ConnectHandler()来SSH登录⽹络设备
# 通过pandas模块对表格进行读取
import pandas as pd
from netmiko import ConnectHandler
#该函数读取表格数据,将数据其转为合适的形式用于函数调用
def device_list(xlsx):
devs_df = pd.read_excel(xlsx)
devs = devs_df.to_dict(orient='records')#按照表头:值的方式转为字典
dev_infos = []
for i in devs:
# 取出配置备份的命令、文件名、是否提权,并用del 将其从字典中删除,并将密码转为字符串(从表格中取出来是int)
backup_cmd = i['backup_cmd']
fonfig_file = i ['config_file']
del i['backup_cmd']
del i['config_file']
i['password']=str(i['password'])
# 删除配置备份命令后的字典就是netmiko登录设备所需的信息
dev = i
dev_infos.append((dev, backup_cmd,fonfig_file))
return dev_infos
#该函数主要使用send_command方法和send_config_from_file方法进行查看配置和下发配置
def network_device_backup(dev,cmd,config_file):
with ConnectHandler(**dev) as conn:
conn.enable()
#进行配置下发
try:
push_output = conn.send_config_from_file(config_file)#自动下发配置
save_output = conn.save_config()#保存配置
except Exception as e:
print('{}配置推送发生异常,使用的配置文件为:{},异常信息:{}'.format(dev['host'], config_file, e))
#进行配置备份
output = conn.send_command(command_string=cmd)
file_name = '{}.txt'.format(dev['host'])
with open(file_name,mode='w',encoding='utf-8') as f:
f.write(output)
print('{}执行备份成功'.format(dev['host']))
def batch_backup(inventory_file):
dev_infos = device_list(inventory_file)
for dev_info in dev_infos:
dev = dev_info[0]
cmd = dev_info[1]
config_file = dev_info[2]
network_device_backup(dev,cmd,config_file)
if __name__ == '__main__':
batch_backup('device_list.xlsx')
上方是正确的、ConnectHandler()函数需要的格式,从表格中读取的password是int,需要转为字符串
对应表格的数据
项目列表
配置下发成功
三、总结
相比于paramiko,netmiko有着更加简化的操作和更加针对网络设备的高阶封装,例如时延、回显、提权等等都会帮你自动完成。其核心函数在我看来有send_command()、send_config_set()两种,前者主要用于查看,执行命令后会持续收集回显,直至收到网络设备提示符;后者可以自动进入设备的config模式进行配置,之后还会自动退出config模式。熟悉了一种脚本流程后就可以适当修改,还可以根据实际需求来重写其中的一些方法。
更多有关netmiko的详细知识
https://zhuanlan.zhihu.com/p/541592293