1. 基础配置
目录结构如下:
.
|-- config.yaml #配置文件,定义设备库的路径,线程等
|-- inventory
| |-- defaults.yaml #所有设备默认配置
| |-- groups.yaml #组内设备共有配置
| |-- hosts.yaml #单个设备配置
|-- main.py #运行文件
config.yaml 内容如下:
---
inventory:
plugin: SimpleInventory
options:
host_file: "inventory/hosts.yaml"
group_file: "inventory/groups.yaml"
defaults_file: "inventory/defaults.yaml"
runner:
plugin: threaded
options:
num_workers: 100
hosts.yaml 内容如下:
---
R1.cc:
hostname: 10.0.0.241
port: 22
platform: cisco_ios
groups:
- router
data:
interfaces: {"Gi0/3": "10.0.0.241/24"}
CS1.cc:
hostname: 10.0.0.242
platform: cisco_ios
groups:
- switch
AS1.cc:
hostname: 10.0.0.243
platform: cisco_ios
groups:
- access
- switch
AS2.cc:
hostname: 10.0.0.244
platform: cisco_ios
groups:
- access
- switch
groups.yaml 内容如下:
---
access:
data:
vlans:
10: pc
20: phone
30: printer
router:
data:
switch:
data:
defaults.yaml 内容如下:
---
username: user
password: password
main.py 内容如下:(注:以下代码只适合nornir 3.0以上,因新版nornir的plugin需要额外安装。)
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")
#print(nr.inventory.hosts)
#print(nr.inventory.groups)
#print(host["vlans"])
host = nr.inventory.hosts["AS2.cc"]
assw = nr.filter(F(groups__contains="access"))
result = assw.run(netmiko_send_command, command_string="sh ip int brief")
print_result(result)
2. 运行测试
$ python main.py
netmiko_send_command************************************************************
* AS1.cc ** changed : False ***************************************************
vvvv netmiko_send_command ** changed : False vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
Interface IP-Address OK? Method Status Protocol
GigabitEthernet0/0 unassigned YES unset up up
GigabitEthernet0/1 unassigned YES unset up up
GigabitEthernet0/2 unassigned YES unset up up
GigabitEthernet0/3 10.0.0.243 YES manual up up
GigabitEthernet1/0 unassigned YES unset up up
GigabitEthernet1/1 unassigned YES unset up up
GigabitEthernet1/2 unassigned YES unset up up
GigabitEthernet1/3 unassigned YES unset up up
^^^^ END netmiko_send_command ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* AS2.cc ** changed : False ***************************************************
vvvv netmiko_send_command ** changed : False vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
Interface IP-Address OK? Method Status Protocol
GigabitEthernet0/0 unassigned YES unset up up
GigabitEthernet0/1 unassigned YES unset up up
GigabitEthernet0/2 unassigned YES unset up up
GigabitEthernet0/3 10.0.0.244 YES manual up up
GigabitEthernet1/0 unassigned YES unset up up
GigabitEthernet1/1 unassigned YES unset up up
GigabitEthernet1/2 unassigned YES unset up up
GigabitEthernet1/3 unassigned YES unset up up
Vlan1 unassigned YES manual administratively down down
^^^^ END netmiko_send_command ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^