安装相关模块
pip3 install netmiko
pip3 install napalm
pip3 install nornir
pip3 install nornir_utils
pip3 install nornir_napalm
pip3 install nornir_netmiko
pip3 install textfsm
创建相关配置文件(config.yml,defaults.yaml,groups.yaml,hosts.yaml)
config.yml
---
inventory:
plugin: SimpleInventory
options:
host_file: "hosts.yaml"
group_file: "groups.yaml"
defaults_file: "defaults.yaml"
runner:
plugin: threaded
options:
num_workers: 100
defaults.yaml
---
username: xxx
password: 'xxx'
groups.yaml
---
huawei_test:
platform:huawei
hosts.yaml
---
test1:
hostname: 192.168.x.x
username: xxx
password: 'xxx'
groups:
- huawei_test
python输出device信息:
from nornir import InitNornir
from nornir_netmiko import netmiko_send_command
from nornir_utils.plugins.functions import print_result
from nornir.core.filter import F
nr = InitNornir(config_file="config.yaml")
def dis_device(group,cmd):
group = nr.filter(F(groups__contains=group))
results = group.run(netmiko_send_command, command_string=cmd,use_textfsm=True)
for key in results.keys:
res = results[key].result
ip = group.inventory.hosts[key].hostname
dis_device('huawei_test','display device')
#use_textfsm=True ,如果模板存在就按照模板显示
#路径 ...../site-packages/ntc-templates/templates
#自定义模板,templates文件夹下
创建huawei_display_device.textfsm:
Value Filldown device_name (.+)
Value Filldown Slot (\w+)
Value Type (\S+)
Value Online ([a-zA-Z]+)
Value Register ([a-zA-Z]+)
Value Status ([a-zA-Z]+)
Value Role ([a-zA-Z]+)
Value LsId (\d+)
Value Primary([a-zA-Z]+)
Start
^${device_name}\s+Device\s+Status
^${Slot}\s+${Type}\s+${Online}\s+${Register}\s+${Status}\s+${Role}\s+${LsId}\s+${Primary}\s+ -> Record
EOF
同时在templates文件夹的index文件添加一行
huawei_display_device.textfsm, .* ,huawei ,disp[[lay]] dev[[ice]]