def main(): # Initialize Nornir object using default "SimpleInventory" plugin nr = InitNornir() nornir_set_creds(nr) result = nr.run( task=os_upgrade, num_workers=20, ) std_print(result) # Filter to only a single device nr_ios = nr.filter(hostname="cisco1.domain.com") aggr_result = nr_ios.run(task=set_boot_var) # If setting the boot variable failed (assumes single device at this point) for hostname, val in aggr_result.items(): if val[0].result is False: sys.exit("Setting the boot variable failed") # Verify the boot variable result = nr_ios.run( task=netmiko_send_command, command_string="show run | section boot", num_workers=20, ) std_print(result) continue_func()
def main(): # Initialize Nornir object using default "SimpleInventory" plugin nr = InitNornir() nornir_set_creds(nr) result = nr.run( task=os_upgrade, num_workers=20, ) std_print(result) # Filter to only a single device nr_ios = nr.filter(hostname="cisco1.domain.com") aggr_result = nr_ios.run(task=set_boot_var) # If setting the boot variable failed (assumes single device at this point) for hostname, val in aggr_result.items(): if val[0].result is False: sys.exit("Setting the boot variable failed") # Verify the boot variable result = nr_ios.run( task=netmiko_send_command, command_string="show run | section boot", num_workers=20, ) std_print(result) continue_func() # Save the config result = nr_ios.run( task=netmiko_send_command, command_string="write mem", ) std_print(result) # Reload continue_func(msg="Do you want to reload the device (y/n)? ") result = nr_ios.run( task=netmiko_send_command, use_timing=True, command_string="reload", ) # Confirm the reload (if 'confirm' is in the output) for device_name, multi_result in result.items(): if 'confirm' in multi_result[0].result: result = nr_ios.run( task=netmiko_send_command, use_timing=True, command_string="y", ) print("Devices reloaded")
#export NET_TEXTFSM=/Users/pmorvay/Documents/Cisco/Devnet/misc/nornir/ntc-templates/templates from pprint import pprint from colorama import Fore import time from nornir import InitNornir nr = InitNornir(config_file="config.yaml") pprint(nr.inventory.hosts) pprint(nr.inventory.groups) from nornir.plugins.functions.text import print_result from nornir.plugins.tasks.networking import netmiko_send_command results = nr.run(task=netmiko_send_command, command_string="show ip int brief | ex una") print_result(results) # remove text_fsm # NET_TEXTFSM= results = nr.run(task=netmiko_send_command, command_string="show version", use_textfsm=True) print_result(results) from nornir.plugins.tasks.networking import napalm_get results = nr.run(task=napalm_get, getters=["facts", "interfaces"]) print_result(results) for host in nr.inventory.hosts.values(): print(f"{host.name} connections: {host.connections}")
def show_cmds(task): cmds = task.host.data['cmds'] max_loops = 180 / 0.2 outputs = '' for cmd in cmds: show_result = task.run(netmiko_send_command, command_string=cmd, max_loops=max_loops) outputs = outputs + '\n' + cmd + '\n\n' + show_result.result + '\n' # 获取巡检当天时间 the_day = datetime.date(datetime.utcnow()) # 用设备名命名结果 log_name = task.host.name + '-(' + task.host.hostname + ')' + '.txt' # 设置存放巡检结果位置 folder = '巡检目录' + str(the_day) file_name = os.path.join(folder, log_name) if not os.path.exists(folder): os.mkdir(folder) # 调用 write_file 写入文件 task.run(write_file, filename=file_name, content=str(outputs)) # 打包结果 zip_name = folder + '.zip' zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) zipdir(folder, zipf) zipf.close() results = nr.run(task=show_cmds) print_result(results)
#!/usr/bin/env python from nornir import InitNornir from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result nr = InitNornir() result = nr.run(task=netmiko_send_command, command_string="show ip route") watched_routes = ['192.168.0.13'] # 1. For loop for each device """ for device in result: print(device) """ # 2. nested loop for device result # why do we need result[device] instead of just device? """ for device in result: print('Device: ' + device) for output in result[device]: print(output) """ # 3. Detect if a route disappeared from the table # why do we need str(output) instead of just output for device in result: print(device + ":")
from nornir import InitNornir from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result import colorama from colorama import Fore, Style print("\n") print(Fore.YELLOW + "#" * 70 + Style.RESET_ALL) print(" " * 20 + "Welcome to " + Fore.RED + "Nornir!" + Style.RESET_ALL) print(" " * 15 + "This is a Dynamic script!") print("\n Please enter the commands you wish to execute, separated by commas") print("Example: " + Fore.GREEN + "< show ip int brief, show ip route, show version >") print(Fore.YELLOW + "#" * 70 + Style.RESET_ALL) commands = input ("\nEnter Commands: ") cmds = commands.split(",") for cmd in cmds: nr = InitNornir() result = nr.run( task=netmiko_send_command, command_string=cmd ) print_result(result)
config_dir = "config-archive" #create variable for timestamped subdirectory with the day's date date_dir = config_dir + "/" + str(date.today()) #create variable within the date directory named after the command executed command_dir = date_dir + "/" + folder #use pathlib to create directory structure using the above variables pathlib.Path(config_dir).mkdir(exist_ok=True) pathlib.Path(date_dir).mkdir(exist_ok=True) pathlib.Path(command_dir).mkdir(exist_ok=True) #use scrapli to deploy commands and save output to the variable "r" r = task.run(task=send_command, command=cmd) #write the output to a textfile taking the output of the "r" variable as the input #name the file after the devices hostname and appended that to ".txt" task.run( task=write_file, content=r.result, filename=f"" + str(command_dir) + "/" + task.host.name + ".txt", ) #initialise Nornir and specify the configuration file to use nr = InitNornir(config_file="config.yaml") #instruct Nornir to execute the "backup_configurations" function create above result = nr.run(name="Creating Backup Archive", task=backup_configurations) #clear the terminal screen os.system(clear_command) #print "Archive Created" in Green text once task has completed print(Fore.GREEN + "Archive Created")
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(F(groups__contains="eos") | F(groups__contains="nxos")) result = nr.run(task=configure_vlans, vlan_id="123", vlan_name="ntp_vlan") print_result(result)
def main(): nr = InitNornir(config_file="config.yaml") nr = nr.filter(name="srx2") agg_result = nr.run(task=junos_acl) print_result(agg_result)
def subtask_instance_started(self, task: Task, host: Host) -> None: pass # to keep example short and sweet we ignore subtasks def subtask_instance_completed( self, task: Task, host: Host, result: MultiResult ) -> None: pass # to keep example short and sweet we ignore subtasks ##### /// START \\\ ##### nr = InitNornir(config_file="config.yaml", dry_run=True) SWPORTS = {} interfaces_switchport_data = nr.run(netmiko_send_command, command_string='show interfaces switchport') for switch, resuslt in interfaces_switchport_data.items(): #print(switch) interfaces_list = parse_output(platform="cisco_ios", command="show interfaces switchport", data=str(resuslt[0])) SWPORTS[switch] = interfaces_list mac_address_table_data = {} nr_with_processors = nr.with_processors([SaveResultToDict(mac_address_table_data), PrintResult()]) nr_with_processors.run(task=napalm_get, getters=["mac_address_table"]) interfaces_data = {} nr_with_processors = nr.with_processors([SaveResultToDict(interfaces_data), PrintResult()]) nr_with_processors.run(task=napalm_get, getters=["interfaces"]) print("TRYING TO FIND MAC: {}".format(MAC_TO_FIND))
def main(): nr = InitNornir(config_file='dec-config.yaml') agg_result = nr.run(task=show_version) for hostname, multi_result in agg_result.items(): print(hostname, multi_result[0].result)
def getHosts(): #whatever you need to do to return the hosts dict yml = ruamel.yaml.YAML(typ="safe") hosts_file = "inventory/hosts2.yaml" with open(hosts_file, "r") as f: hosts_dict = yml.load(f) return hosts_dict def buildHosts(hosts_dict): #remember no groups or defaults hosts = Hosts() for n, h in hosts_dict.items(): h.pop('groups', None) hosts[n] = _get_inventory_element(Host, h, n, {}) return hosts #you will still need a default dictionary to load, but overwrite after nr = InitNornir(config_file='config.yaml', ) print(len(nr.inventory.hosts)) setattr(nr, 'inventory', Inventory(hosts=buildHosts(getHosts()), groups={}, defaults={})) print(len(nr.inventory.hosts)) agg_result = nr.run(task=show_version) for hostname, multi_result in agg_result.items(): print(hostname, multi_result[1].result)
from nornir import InitNornir from nornir.plugins.tasks import networking from nornir.core.filter import F from nornir.plugins.functions.text import print_result def netmiko_direct(task): print(task.host.username) # Manually create Netmiko connection net_connect = task.host.get_connection("netmiko", task.nornir.config) print() print("#" * 80) print(net_connect.find_prompt()) print("#" * 80) print() if __name__ == "__main__": nr = InitNornir(config_file="config.yaml") result = nr.run(task=netmiko_direct, num_workers=1) print_result(result)
def n_cmd_parser(): # Initialize Nornir and define the inventory variables. nr = InitNornir( inventory={ "options": { "host_file": "inventory/hosts.yaml", "group_file": "inventory/groups.yaml", "defaults_file": "inventory/defaults.yaml", } }) """ The following block of lists are the supported parsers per OS based on the website: https://pubhub.devnetcloud.com/media/genie-feature-browser/docs/#/parsers """ ios_commands = [ "show version", "show ip route", "show inventory", "show ip interface", "show vtp status", "show users", "show ntp associations", "cbd", # fake command for testing purposes ] nxos_commands = [ "show version", "show feature", "show ip arp", "show ip route", "show ip arp", "show inventory", "show ip interface", "show vtp status", "show users", "show ntp associations", "show lldp neighbors detail", ] """ The following block of code assigns a filter based on platform to a variable. This variable is used later on to apply logic in for loops """ ios_devices = nr.filter(platform="ios") nxos_devices = nr.filter(platform="nxos") iosxr_devices = nr.filter(platform="iosxr") print(iosxr_devices) # IOS Platform Block for host in ios_devices.inventory.hosts.items(): # Assign the hostname to a variable from the host tuple hostname = host[0] # Starting processing of a host print("** Start Processing Host: " + str(hostname)) # log_file.write("** Start Processing Host: " + str(hostname) + "\n") for cmd in ios_commands: # Start collecting the command outputs print("Processing " + str(cmd) + " Command ... ") # log_file.write("Processing " + str(cmd) + " config ... " + "\n") # Execute the n_genie function configs = nr.run(task=n_genie, command=cmd, num_workers=1) # Debur print print(configs) # NXOS Platform Block for host in nxos_devices.inventory.hosts.items(): # Assign the hostname to a variable from the host tuple hostname = host[0] # Starting processing of a host print("** Start Processing Host: " + str(hostname)) # log_file.write("** Start Processing Host: " + str(hostname) + "\n") for cmd in nxos_commands: # Start collecting the command outputs print("Processing " + str(cmd) + " Command ... ") # log_file.write("Processing " + str(cmd) + " config ... " + "\n") # Execute the n_genie function configs = nr.run(task=n_genie, command=cmd, num_workers=1) print(configs)
from nornir import InitNornir from nornir.plugins.tasks.networking import netmiko_file_transfer from nornir_utilities import nornir_set_creds, std_print # Initialize Nornir object using default "SimpleInventory" plugin nr = InitNornir() nornir_set_creds(nr) test_file = 'test_file4.txt' result = nr.run( task=netmiko_file_transfer, source_file=test_file, dest_file=test_file, direction='put', num_workers=20, ) std_print(result)
#!/usr/bin/env python from nornir import InitNornir from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result # If you are using Nornir3, there are some changes: # https://github.com/twin-bridges/nornir_course/blob/master/nornir3_changes.md # Please pip install: pip install nornir_utils nornir_netmiko # Then replace the 2 nornir.plugin imports with below: #from nornir_utils.plugins.functions import print_result #from nornir_netmiko import netmiko_send_command nr = InitNornir() result = nr.run(task=netmiko_send_command, command_string="show arp") print_result(result)
task=napalm_cli, commands=diff_cmds, ) """ def commands(task): test_commands = ["show ip route"] task.run( name="Test some routing commands", task=napalm_cli, commands=test_commands, ) #def rollback(task): # rollback_cmds = ["configure replace flash:rollback-0", "write memory"] # task.run( # name="Run diff between running config and rollback config.", # task=napalm_cli, # commands=rollback_cmds, # ) result = nr.run(task=commands) print_result(result)
from nornir_netmiko.tasks.netmiko_send_command import netmiko_send_command import pprint import ipdb import json name = 'cisco' nr = InitNornir(config_file="config.yaml") def title(n): return n get_info = nr.run( task=netmiko_send_command, command_string="show ip route" ) get_info_napalm = nr.run( task=napalm_get, getters=["facts"] ) # ipdb.set_trace() # print_result(get_info_napalm) # pprint.pprint(get_info_napalm["rtr1"][0].result) if __name__ == '__main__': title()
r = task.run(netmiko_send_command, delay_factor=4, command_string="show version", use_textfsm=True) task.host["version"] = r.result cdp = task.host['cdp'] subn = task.host['mgmt'][4] gateway = task.host['gateway'][2] image = task.host['version'][0]['version'] host = task.host['version'][0]['hostname'] filename = 'H:/Scripts/TEXTFSM/' + name + '.csv' write_header = not os.path.exists(filename) with open(filename, 'a') as csvfile: headers = [ 'Hostname', 'IP Address', 'Subnet Mask', 'Gateway IP', 'CDP', 'Image' ] writer = csv.DictWriter(csvfile, fieldnames=headers) if write_header: writer.writeheader() writer = csv.writer(csvfile) csvdata = (host, task.host.hostname, subn, gateway, cdp, image) writer.writerow(csvdata) result = nr.run(task=get_facts) print_result(result) #import ipdb #ipdb.set_trace()
from nornir import InitNornir from nornir_utils.plugins.functions import print_result from nornir_utils.plugins.tasks.files import write_file from nornir_netmiko import netmiko_send_command from nornir.core.filter import F def logging_show_run(task): cmd = 'show run' output = task.run( name='show run', task=netmiko_send_command, command_string=cmd) task.run( task=write_file, name="Write", filename=f"output/nornir/{task.host.hostname}.cfg", content=output.result, ) nr = InitNornir(inventory={"options": {"host_file": f"inventory/nornir/inventory-30.yaml"}},) nr.run(logging_show_run)
from nornir import InitNornir from nornir.core.filter import F from nornir.plugins.tasks.networking import netmiko_send_command from nornir.plugins.functions.text import print_result from pprint import pprint nr=InitNornir(config_file="../../config.yaml") pprint(nr.inventory.hosts.items()) nr=nr.filter(F(groups__contains="eos")) pprint(nr.inventory.hosts.items()) r=nr.run(task=netmiko_send_command, command_string="show interface status", use_textfsm=True) print_result(r)
import os from nornir import InitNornir from nornir_netmiko import netmiko_send_command from nornir_utils.plugins.functions import print_result nr = InitNornir(config_file="nornir.yaml") # Code so automated tests will run properly nr.inventory.groups["cisco"].password = os.environ["NORNIR_PASSWORD"] results = nr.run(task=netmiko_send_command, command_string="show ip int brief") print_result(results)
good_output = (f"{task.host}: {ospf_intf}"\ f" is in Area {short_area} with IP: {ipaddr}"\ f" - neighboring {neigh_ip}") bad_output = (f"ERROR: {task.host}:"\ f" {ospf_intf} (IP = {ipaddr} | MTU = {mtu})"\ f" is in Area {short_area} (Type: {area_type})"\ "- neighbor in DOWN/EXSTART!") if "EXSTART" in state: bad_list.append(bad_output) elif "DOWN" in state: bad_list.append(bad_output) elif "2WAY" in state: good_list.append(good_output) elif "FULL" in state: good_list.append(good_output) except KeyError: bad_output = (f"ERROR: {task.host}:"\ f" {ospf_intf} (IP = {ipaddr} | MTU = {mtu})"\ f" is in Area {short_area} (Type: {area_type}) with no neighbor!") bad_list.append(bad_output) results = nr.run(task=ospf_check) print("[green][u]******** PASSED ********[/u][/green]\n") for good in good_list: print(f"[cyan]{good}[/cyan]") print("\n[red][u]******** FAILED ********[/u][/red]\n") for bad in bad_list: print(f"[red]{bad}[/red]")
def main(): nr = InitNornir(config_file="config.yaml", logging={"enabled": False}) nr = nr.filter(F(groups__contains="nxos")) result = nr.run(task=custom_task) print_result(result)
from nornir import InitNornir from nornir_utils.plugins.functions import print_result from nornir_netmiko.tasks import netmiko_send_config, netmiko_send_command nr = InitNornir( config_file="config.yaml",dry_run=True ) results = nr.run( netmiko_send_command, command_string="sh ip int brief" ) print_result(results)
from nornir import InitNornir from nornir_utils.plugins.functions import print_result from nornir_netmiko.tasks import netmiko_send_command from nornir.core.task import Task, Result def my_netmiko_command(task: Task) -> Result: result = task.run( task=netmiko_send_command, command_string = "show lldp neighbor", use_textfsm=True ) return Result( host=task.host, result=f'Task {task.name} on host {task.host} {"failed" if result.failed else "completed succesfully"}' ) nr = InitNornir(config_file="config.yaml", dry_run=True) results = nr.run(task=my_netmiko_command) print_result(results)
(optional) vrf - Name of vrf. (default=None) (type=string) Examples: Simple example:: > nr.run(task=napalm_ping, > dest='10.1.1.1') Passing some other optional arguments:: > nr.run(task=napalm_ping, > dest='10.1.1.1', source='10.1.1.2', size=1400, count=10) Returns: Result object with the following attributes set: * result (``dict``): list of dictionary with the result of the ping response. Output dictionary has one of following keys "success or error" """ device = task.host.get_connection("napalm", task.nornir.config) result = device.ping(destination=dest, source=source, ttl=ttl, timeout=timeout, size=size, count=count, vrf=vrf) return Result(host=task.host, result=result) result = nr.run(task=napalm_ping, dest='10.91.2.9') print_result(result) result = device.ping( destination=dest, source=source, ttl=ttl, timeout=timeout, size=size, count=count, vrf=vrf )
def main(): nr = InitNornir(config_file="config.yaml", logging={"enabled": False}) result = nr.run(task=my_task) print_result(result)
from nornir import InitNornir def my_task(task): host = task.host print() print(host.hostname) print("-" * 12) print(f"DNS1: {host['dns1']}") print(f"DNS2: {host['dns2']}") print() if __name__ == "__main__": nr = InitNornir() nr.run(task=my_task)
# Reload inventory nr = InitNornir(config_file="/home/nornir-ztp/config.yaml") # Configure SSH keys on network elements ####################################### def gen_ssh_keys(task): # Generate config commands cfg = [ task.run(template_file, path="templates", template="ssh-config.j2").result ] # Configure on hosts task.run(netmiko_send_config, config_commands=cfg) result = nr.run(gen_ssh_keys) print_result(result) # Update SSH keys on server #################################################### subprocess.call("cp /dev/null /home/eve/.ssh/known_hosts", shell=True) for lease_ip in lease_ips: fmt = 'ssh-keyscan {} >> /home/eve/.ssh/known_hosts'.format(lease_ip) subprocess.call(fmt, shell=True) # Find MAC of E0/0 interfaces of elements ###################################### COMMAND = 'show interface eth0/0 | i Hardware is AmdP2' response = nr.run(task=netmiko_send_command, command_string=COMMAND) mac_result = {} for hostname in response: fmt = 'is (\w{4}\.\w{4}\.\w{4})'
from nornir import InitNornir from nornir.plugins.functions.text import print_result, print_title from nornir.plugins.tasks.networking import netmiko_send_config, netmiko_send_command nr = InitNornir(config_file="config.yaml", dry_run=True) def base(ipvzero): ipvzero.run(task=netmiko_send_config, config_file="secure-copy") ipvzero.run(task=netmiko_send_command, command_string="show run | sec ip scp") results = nr.run(task=base) print_title("ENABLING SECURE COPY FOR NAPALM") print_result(results)
from nornir import InitNornir def my_task(task): raise ValueError("An error happened in my_task.") def simple_task(task): print(f"Host: {task.host.name}") if __name__ == "__main__": nr = InitNornir(config_file="config.yaml") aggr_results = nr.run(task=my_task) print() if aggr_results.failed is True: print("Task failed") print(aggr_results.failed) print() vmx1 = aggr_results["vmx1"] print(f"Exception on vmx1: {vmx1.exception}\n") print(f"Failed Hosts:\n{nr.data.failed_hosts}\n") # Recover vmx1 and vmx2 print("Recovering 'vmx1' and 'vmx2'\n") nr.data.recover_host("vmx1") nr.data.recover_host("vmx2")
import os from rich import print from nornir import InitNornir from nornir_napalm.plugins.tasks import napalm_get nr = InitNornir(config_file="nornir.yaml") # Code so automated tests will run properly nr.inventory.groups["nxos"].password = os.environ["NORNIR_PASSWORD"] results = nr.run(task=napalm_get, getters=["bgp_neighbors"]) print() for k, v in results.items(): print("-" * 50) print(k) print(v[0].result) print("-" * 50) print()
from nornir import InitNornir from nornir_scrapli.tasks import netconf_edit_config from nornir_utils.plugins.functions import print_result from nornir_jinja2.plugins.tasks import template_file nr = InitNornir(config_file="nornir_data/config2.yaml") def config_routing(task): routing_template = task.run( task=template_file, name="Buildling Routing Configuration", template="ntp.j2", path="./templates", ) routing_output = routing_template.result task.run(task=netconf_edit_config, target="running", config=routing_output) result = nr.run(task=config_routing) print_result(result)