本篇比较水,只是参照官方文档做一个progress bar,说明如何将nornir与tqdm集成,以添加一种跟踪脚本进度的好方法,而无需在屏幕上打印结果。
先看看效果:
demo.py
```python from typing_extensions import runtime from nornir import InitNornir from nornir.core.plugins.inventory import InventoryPluginRegister
from nornir_netmiko import netmiko_send_command, netmiko_send_config
from nornir_paramiko.plugins.tasks import paramiko_command, paramiko_commands from nornir_utils.plugins.functions import print_result from lab2.cmdb import CMDBInventory
from tqdm import tqdm
InventoryPluginRegister.register("CMDBInventory", CMDBInventory)
device_type改为platform也是兼容的
devices = [ {'ip': '192.168.11.11', 'username': 'python', 'password': '123', 'device_type': 'huawei'}, {'ip': '192.168.11.12', 'username': 'python', 'password': '123', 'platform': 'huawei'}, {'ip': '192.168.11.13', 'username': 'python', 'password': '123', 'platform': 'huawei'}, ]
nr = InitNornir( runner={ "plugin": "threaded", "options": { "num_workers": 100, }, }, inventory={ "plugin": "CMDBInventory", "options": { "devices": devices, }, }, )
commands = ['sys', 'dis this', 'return', 'quit']
一个task也可以调用其他task
def multiple_progress_bar(task, current_bar, other_bar): task.run(task=paramiko_commands, commands=commands)
current_bar.update()
tqdm.write(f"{task.host}: processing...")
other_bar.update()
tqdm.write(f"{task.host}: done!")
with tqdm(total=len(nr.inventory.hosts), desc='processing') as current_bar: with tqdm(total=len(nr.inventory.hosts), desc='other action') as other_bar: nr.run(task=multiple_progress_bar, current_bar=current_bar, other_bar=other_bar)
```
我做出来的效果有点不一样,可能是终端shell的问题。
这个demo主要是为了下一篇做铺垫,所以只能算番外,同时展示了一个task也可以调用其他task,可以通过组合较小的task来构建更复杂的功能。
水完收工!