nornir Pluggable multi-threaded framework with inventory management to help operate collections of devices 项目地址: https://gitcode.com/gh_mirrors/no/nornir
Nornir是一款专为网络自动化设计的纯Python框架,它允许开发者直接利用Python语言进行网络设备管理与任务执行。不同于许多依赖特定领域特定语言(DSL)的自动化工具,Nornir让开发者可以在熟悉的Python环境下进行一切控制,显著提升了调试的便捷性。本指南旨在帮助新手从零开始,了解并成功安装配置Nornir框架。
Nornir是一个强大的多线程自动化框架,专注于简化对网络设备集合的操作。它的设计思路是通过插件机制扩展功能,内置了库存管理系统,能够高效地调度任务至各个设备上。Nornir的核心亮点在于其完全使用Python 3.8或更高版本作为开发语言,这不仅降低了入门门槛,也为自动化脚本带来了无限可能。
Nornir利用Python的灵活性构建了一个可插拔架构,支持自定义插件来扩展其功能,比如添加新的连接方法、任务处理等。该框架本身不直接集成复杂的网络协议实现,但通过灵活的插件系统,可以轻松集成SSH、HTTP等协议用于设备交互。此外,Nornir采用多线程技术提高并发执行效率,并依赖于现代Python生态中的包如requests
、paramiko
(通过插件)等完成远程通信。
确保您的计算机已安装Python 3.8或更高版本。可以通过命令行输入python3 --version
验证Python版本。
打开终端或命令提示符,使用pip(Python的包管理器)安装Nornir。如果你还没有pip,先安装pip。
pip install pip -U # 确保pip是最新的版本
pip install nornir
对于开发环境,推荐使用poetry
以更好地管理项目的依赖。首先,安装poetry:
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -
然后,在项目目录下初始化poetry环境并安装Nornir及相关依赖(如果需要更多插件,可通过poetry add
添加):
cd your_project_directory
poetry init
poetry add nornir
Nornir的库存管理非常灵活,支持多种格式,包括简单的Python文件、YAML或JSON。下面是一个简单的例子,展示如何在Python环境中设置一个基本的库存:
创建一个名为inventory.py
的文件:
from nornir import InitNornir
from nornir.core.filter import F
def main():
nr = InitNornir(config_file="config.yml")
filtered_devices = nr.filter(F(groups__contains='ios'))
print(filtered_devices.inventory.hosts)
if __name__ == "__main__":
main()
同时,你需要创建对应的config.yml
文件来指定库存配置,例如:
inventory:
plugin: "nornir.plugins.inventory.simple.SimpleInventory"
options:
host_file: "hosts.yaml"
groups_file: "groups.yaml"
以及相应的hosts.yaml
和groups.yaml
文件来定义具体的设备信息和分组。
安装完成后,你可以通过运行一个简单的示例脚本来验证Nornir是否正确安装。例如,下面的脚本检查所有设备的 Reachability:
from nornir import InitNornir
from nornir净tasks import netmiko_send_command
from nornir.core.filter import F
nr = InitNornir(config_file="config.yml")
def ping_host(task):
result = task.run(task=netmiko_send_command, command_string="ping google.com")
task.host["facts"]["ping"] = result.result
filtered_devices = nr.filter(F(groups__contains='ios'))
results = filtered_devices.run(task=ping_host)
for hostname, result in results.items():
print(f"{hostname}: {result['facts']['ping']}")
至此,您已经完成了Nornir的安装与基础配置,可以进一步探索其高级特性和编写自己的自动化脚本了。记得根据实际情况调整配置文件和脚本内容,以适应不同的网络环境和需求。
nornir Pluggable multi-threaded framework with inventory management to help operate collections of devices 项目地址: https://gitcode.com/gh_mirrors/no/nornir