|
| 1 | +from nornir.core.task import Task, Result |
| 2 | +from netmiko import ConnectHandler |
| 3 | +from netnir.helpers import device_mapper |
| 4 | + |
| 5 | +"""netmiko (SSH) nornir tasks""" |
| 6 | + |
| 7 | + |
| 8 | +def netmiko_send_commands(task: Task, commands: list()): |
| 9 | + """send show commands to a device via netmiko |
| 10 | +
|
| 11 | + :param task: nornir Task object |
| 12 | + :param commands: a list of commands to execute |
| 13 | +
|
| 14 | + :returns: nornir Result object |
| 15 | + """ |
| 16 | + device_params = { |
| 17 | + "host": task.host.hostname, |
| 18 | + "device_type": device_mapper(os_type=task.host.platform, proto="netmiko"), |
| 19 | + "port": task.host.port, |
| 20 | + "username": task.host.username, |
| 21 | + "password": task.host.password, |
| 22 | + "secret": task.host.connection_options["netmiko"]["extras"].get("secret", None), |
| 23 | + } |
| 24 | + |
| 25 | + with ConnectHandler(**device_params) as conn: |
| 26 | + output = str() |
| 27 | + |
| 28 | + for command in commands: |
| 29 | + output += conn.send_command(command) |
| 30 | + |
| 31 | + return Result(host=task.host, result=output) |
| 32 | + |
| 33 | + |
| 34 | +def netmiko_send_config(task: Task, commands: list()): |
| 35 | + """execute configuration changes on a device via netmiko |
| 36 | +
|
| 37 | + :param task: nornir Task object |
| 38 | + :param commands: a list of commands to execute |
| 39 | +
|
| 40 | + :returns: nornir Result object |
| 41 | + """ |
| 42 | + device_params = { |
| 43 | + "host": task.host.hostname, |
| 44 | + "device_type": device_mapper(os_type=task.host.platform, proto="netmiko"), |
| 45 | + "port": task.host.port, |
| 46 | + "username": task.host.username, |
| 47 | + "password": task.host.password, |
| 48 | + "secret": task.host.connection_options["netmiko"]["extras"].get("secret", None), |
| 49 | + } |
| 50 | + |
| 51 | + with ConnectHandler(**device_params) as conn: |
| 52 | + output = conn.send_config_set(commands) |
| 53 | + output += conn.save() |
| 54 | + |
| 55 | + return Result(task.host, result=output) |
0 commit comments