napalm入门
参考阅读
网络工程师的Python之路–汇总
实验拓扑
一如既往,但是只使用一台设备
需求
- 通过napalm模块来统计switch的up接口
- 输出接口的mac地址
程序
检查type()
from napalm import get_network_driver
import json
driver = get_network_driver('ios')
SW1 = driver('192.168.2.223','eichi','123')
SW1.open()
interface = SW1.get_interfaces()
interface_json = json.dumps(interface,indent=2)
print(type(interface))
print(type(interface_json))
运行以上py程序,检查输出的type,可见直接调用NAPALM的API后输出的内容是dict 打印这两个变量,第二个的json输出其实是字符串类型
完成需求
from napalm import get_network_driver
import json
ip = '192.168.2.223'
driver = get_network_driver('ios')
SW1 = driver(ip,'eichi','123')
SW1.open()
interface = SW1.get_interfaces()
interface_json = json.dumps(interface,indent=2)
print("ip为"+ ip +"的switch以下接口的状态是up/up,其MAC地址如下所示")
for key,value in interface.items():
if value['is_up'] == True:
print(key + "的MAC地址为: " + value["mac_address"])
举例:
"Ethernet2/3": {
"is_enabled": true,
"is_up": true,
"description": "",
"mac_address": "AA:BB:CC:00:06:32",
"last_flapped": -1.0,
"mtu": 1500,
"speed": 10
},
key是Ethernet2/3;
对应的value是{
"is_enabled": true,
"is_up": true,
"description": "",
"mac_address": "AA:BB:CC:00:06:32",
"last_flapped": -1.0,
"mtu": 1500,
"speed": 10
}
若想要匹配接口的状态就是value["is_up"],若这个值为True,那么就说明这个接口是up的
运行程序: 与设备上的状态进行检查对比,可见与预期相符
扩展需求
类似地,想要打印出arp-table 程序如下
from napalm import get_network_driver
import json
ip = '192.168.2.223'
driver = get_network_driver('ios')
SW1 = driver(ip,'eichi','123')
SW1.open()
arp = SW1.get_arp_table()
arp_json = json.dumps(arp,indent=2)
print(arp_json)
print(arp)
运行程序如下
总结
根据调用napalm模块的API来完成特殊化的需求
|