مقدمه
Nornir یک فریمورک Python برای اتوماسیون شبکه است. بر خلاف Ansible، Nornir کد Python خالص است — شما کد Python مینویسید (نه playbook YAML) تا دستگاههای شبکه را خودکار کنید.
نصب
BASH
pip install nornir nornir-utils nornir-netmiko nornir-napalmاسکریپت پایه Nornir
PYTHON
from nornir import InitNornir
from nornir_netmiko.tasks import netmiko_send_command
from nornir_utils.plugins.functions import print_result
nr = InitNornir(
runner={"plugin": "threaded", "options": {"num_workers": 20}},
inventory={
"plugin": "SimpleInventory",
"options": {
"host_file": "inventory/hosts.yaml",
"group_file": "inventory/groups.yaml",
},
},
)
# اجرا روی همه دستگاهها بهطور همزمان
result = nr.run(
task=netmiko_send_command,
command_string="show version"
)
print_result(result)اعمال تغییرات پیکربندی
PYTHON
from nornir_netmiko.tasks import netmiko_send_config
def configure_ntp(task):
ntp_config = [
"ntp server 192.168.1.100 prefer",
"ntp server 192.168.1.101",
]
task.run(task=netmiko_send_config, config_commands=ntp_config)
task.run(task=netmiko_send_command, command_string="write memory")
result = nr.filter(F(groups__contains="cisco_ios")).run(task=configure_ntp)استفاده از NAPALM برای داده ساختارمند
PYTHON
from nornir_napalm.plugins.tasks import napalm_get
result = nr.run(task=napalm_get, getters=["interfaces", "bgp_neighbors"])
for hostname, task_result in result.items():
interfaces = task_result[0].result["interfaces"]
for iface_name, iface_data in interfaces.items():
if not iface_data["is_up"]:
print(f"{hostname}: {iface_name} Down است")خلاصه
- Nornir کد Python خالص است — برای منطق پیچیده استفاده کنید
- بهطور پیشفرض multi-threaded است — روی شبکههای بزرگ سریع است
- از Netmiko برای اتصالات SSH و NAPALM برای داده ساختارمند استفاده کنید
- همیشه خرابیها را مدیریت کنید
