自动方式
默认情况下,连接是自动处理的:
from nornir import InitNornir from nornir_napalm.plugins.tasks import napalm_get import pprint
nr = InitNornir(config_file="handling_connections/config.yaml") rtr = nr.filter(name="rtr00") r = rtr.run( task=napalm_get, getters=["facts"] ) pprint.pprint(r["rtr00"][0].result)
{'facts': {'fqdn': 'localhost', 'hostname': 'localhost', 'interface_list': ['Ethernet1', 'Ethernet2', 'Ethernet3', 'Ethernet4', 'Management1'], 'model': 'vEOS', 'os_version': '4.15.5M-3054042.4155M', 'serial_number': '', 'uptime': '...', 'vendor': 'Arista'}}
手动方式
在某些情况下,您可能需要手动管理连接。为此,您可以使用open_connection,close_connection,close_connections和Nornir.close_connections。例如:
def task_manages_connection_manually(task): task.host.open_connection("napalm", configuration=task.nornir.config) r = task.run( task=napalm_get, getters=["facts"] ) task.host.close_connection("napalm") nr = InitNornir(config_file="handling_connections/config.yaml") rtr = nr.filter(name="rtr00") r = rtr.run( task=task_manages_connection_manually, ) # this time the result in position 0 is the connection print(f"Connection succeeded: {not r['rtr00'][0].failed}") # and the result in position 1 is the result for napalm_get
Connection succeeded: True {'facts': {'fqdn': 'localhost', 'hostname': 'localhost', 'interface_list': ['Ethernet1', 'Ethernet2', 'Ethernet3', 'Ethernet4', 'Management1'], 'model': 'vEOS', 'os_version': '4.15.5M-3054042.4155M', 'serial_number': '', 'uptime': '...', 'vendor': 'Arista'}}
指定连接参数
使用open_connection时,可以指定所需的任何参数。如果不这样做,或者让nornir自动打开连接,则nornir将从inventory中读取这些参数。如果要在不同的连接上重用它们,则可以在对象级别指定标准属性,也可以为每个连接覆盖它们。例如:
!sed '2,35!d' ../../tests/inventory_data/hosts.yaml
dev1.group_1: port: 65020 hostname: localhost username: password: a_password platform: eos data: my_var: comes_from_dev1.group_1 www_server: nginx role: www nested_data: a_dict: a: 1 b: 2 a_list: [1, 2] a_string: asdasd groups: - group_1 connection_options: paramiko: port: 65020 hostname: username: root password: docker platform: linux extras: {} dummy: hostname: dummy_from_host port: username: password: platform: extras: blah: from_host