Netmiko 是作者 Kirk Byers 在 2014 年底基于 paramiko 开始开发的。它做了很多改进,如精简了 show (华为就是 display )命令的执行和回显内容的读取,简化了设备配置命令,支持了多厂商的设备和平台。

Netmiko 模块 4 种设备配置函数, @弈心大神 文章中详细介绍,大家可先行认真阅读。我阅读后简述如下:
通过 PC(192.168.242.2,Python所在),连接 Layer3Switch-1(192.168.242.12) ,完成如下三个小目标。
display interface description | include GE0/0/[12][^0-9]
# 正则表达式在网络运维中是一把利器,稍作解释:
# 因为 LSW2 的 0 板是有 24 端口,我们只关注 GE0/0/1 和 GE0/0/2。
# 为了回显简洁,我们使用了 include 进行过滤。(公众号:释然IT杂谈)
# 正则表达式 GE0/0/[12][^0-9] 中 [12] 表示字符 1 或者 2 ,[^0-9] 表示非0-9。
# 于是 GE0/0/[12][^0-9] 只会匹配 GE0/0/1 和 GE0/0/2 ,不会匹配 GE0/0/3 等其它。
上述三点前序文章介绍过,这里从略。
netmiko 模块的脚本相对于 paramiko 真是精简太多了,有惊艳之感!
from netmiko import ConnectHandler
sw1 = {'device_type':'huawei',
'ip':'192.168.242.12',
'username':'python',
'password':'123'}
commands = ['interface GigabitEthernet 0/0/1', 'description descby_send_config_set()']
with ConnectHandler(**sw1) as connect:
print ("已经成功登陆交换机" + sw1['ip'])
# 公众号:释然IT杂谈
print('===实验目的(1),交互形式推送一条指令。')
output = connect.send_command('display interface description | include GE0/0/[12][^0-9]')
print(output)
print('===实验目的(2),列表形式推送多条指令。')
output = connect.send_config_set(commands)
print(output)
print('===实验目的(3),文件形式推送多条指令。')
output = connect.send_config_from_file('netmiko-config-lab2.txt')
print(output)
print('===最后再检查配置')
output = connect.send_command('display interface description | include GE0/0/[12][^0-9]')
print(output)
# 华为设备的保存配置save后需要输入y进行确认,后面实验再演示。

display interface description | include GE0/0/[12][^0-9]
小伙伴想执行其他友商设备怎么办,这里以思科为例略微调整成思科类型和命令就行。
发表评论