How to use the nornir.InitNornir function in nornir

To help you get started, we’ve selected a few nornir examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github writememe / day-one-net-toolkit / collection-toolkit.py View on Github external
lldp_nei_headers = [
        "Local Hostname",
        "Local Port",
        "Remote Hostname",
        "Remote Port",
    ]
    # Write headers on the top line of the file
    lldp_nei_ws.append(lldp_nei_headers)
    # Create Users worksheet
    users_ws = wb.create_sheet("Users")
    # Statically assign headers
    users_headers = ["Hostname", "Username", "Level", "Password", "SSH Keys"]
    # Write headers on the top line of the file
    users_ws.append(users_headers)
    # 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 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")
    junos_devices = nr.filter(platform="junos")
    eos_devices = nr.filter(platform="eos")
github twin-bridges / nornir_course / bonus1 / collateral / netmiko_direct_task / netmiko_direct.py View on Github external
def netmiko_direct(task):

    # Manually create Netmiko connection
    net_connect = task.host.get_connection("netmiko", task.nornir.config)
    print()
    print("#" * 80)
    print(net_connect.find_prompt())
    output = net_connect.send_command("show ip int brief")
    print(output)
    print("#" * 80)
    print()


if __name__ == "__main__":
    nr = InitNornir(config_file="config.yaml")
    ios_filt = F(groups__contains="ios")
    nr = nr.filter(ios_filt)
    nr.run(task=netmiko_direct, num_workers=1)
github twin-bridges / nornir_course / bonus2 / collateral / netbox / nbox.py View on Github external
def main():
    nr = InitNornir(
        config_file="config.yaml",
        inventory={
            "options": {"nb_token": NBOX_TOKEN, "nb_url": "https://netbox.lasthop.io"}
        },
    )
    nr.run(task=nbox_task)
github cldeluna / nornir-config / nornir_config_create.py View on Github external
def main():

    # Get our shov vlan output from each device in our inventory
    send_commands=['show vlan']
    output_dict = nornir_discovery.send_napalm_commands(send_commands, show_output=True, debug=False)

    # Set the TextFSM template we will be using to parse the show vlan output so we get it back in a way we can use
    template_filename = 'cisco_ios_show_vlan.template'

    # Initialize the vlan dictionary we will send to our Jinja2 template
    j2_data_dict = {}

    # ======= Define the Nornir Environment ========
    nornir_instance = InitNornir()


    # For each device lets build out the list of vlans which must be removed
    for dev, output in output_dict.items():

        parsed_results = nornir_discovery.parse_with_texfsm(output, template_filename, debug=False)
        remove_vlan_list = []

        # For each Vlan we found configured on the device
        for vlan_data in parsed_results:
            # We are only interested in vlans between 1 and 999
            # vlan_data[0] is the vlan number
            if 1 < int(vlan_data[0]) < 1000:

                ints_in_vlan = len(vlan_data[3])
github twin-bridges / nornir_course / class5 / exercises / exercise3 / exercise3.py View on Github external
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(name="srx2")
    nr.run(task=junos_acl)
github cldeluna / nornir-config / nornir_discovery.py View on Github external
debug is an optional argument which prints out values to assist in debugging.

    :param cmds: list of commands to execute on each device
    :param show_output: Boolean which defaults to False.
        When True values the Ansible-like run output will be printed to stdout
    :param debug: Boolean which defaults to False. When True values will be printed to stdout
    :return: output_dict
    """

    output_dict = {}

    if isinstance(cmds, list):

        # Instantiate the Nornir environment (based on our inventory hosts.yaml and groups.yaml
        # and config.yaml, if it exists, files)
        nornir_instance = InitNornir(dry_run=True)

        # Execute the commands in the 'cmds' variable using the napalm_cli plugin
        cli_result = nornir_instance.run(napalm_cli, commands=cmds)

        # Our goal is to build a dictionary of dictionaries
        # so that it can be referenced a bit more simply as output_dict[device1][showcmd1]

        # Iterate over the first set of keys in the results object which will represent each device
        if debug: print(cli_result.keys())
        for dev_key in cli_result.keys():

            # Iterate over one or more results keys which represent the show command or show commands
            # extracted from each device
            # Alternatively we could use the cmds list to build the inside dict
            # but just in case something goes wrong, lets build it from the actual keys
            if debug:
github twin-bridges / nornir_course / class4 / exercises / exercise5 / exercise5c.py View on Github external
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(name="arista4")

    # Capture current running configuration
    agg_result = nr.run(
        task=networking.napalm_get, getters=["config"], retrieve="running"
    )
    arista4_result = agg_result["arista4"][0].result
    arista4_running_config = arista4_result["config"]["running"]

    # Configure a new loopback
    config = """interface loopback123
  description verycoolloopback"""
    agg_result = nr.run(task=networking.napalm_configure, configuration=config)
    print_result(agg_result)

    print()
github twin-bridges / nornir_course / bonus1 / collateral / napalm_nxos_ssh / napalm_nxos.py View on Github external
from nornir import InitNornir
from nornir.core.filter import F


def direct(task):

    # Manually create NAPALM connection
    import ipdb

    ipdb.set_trace()
    napalm = task.host.get_connection("napalm", task.nornir.config)
    conn = napalm.device  # noqa


if __name__ == "__main__":
    nr = InitNornir(config_file="config.yaml")
    filt = F(groups__contains="nxos")
    nr = nr.filter(filt)
    nr.run(task=direct, num_workers=1)
github twin-bridges / nornir_course / bonus2 / exercises / bgp_config_tool_final.py View on Github external
The purpose of this script is to manage all BGP configurations for the NXOS devices.
    This includes prefix lists, route maps and the actual bgp routing configurations. Other config
    items should be left alone. This tool replaces the entire configuration using NAPALM, in order
    to do that safely a configuration checkpoint is taken, and this checkpoint file is copied and
    modified to reflect the desired end state.

    """
    task_list = [
        prepare_interfaces,
        ensure_config_flags,
        get_current_checkpoint,
        render_configurations,
        create_new_checkpoint,
        push_updated_checkpoint,
    ]
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="nxos"))
    for task in task_list:
        result = nr.run(task=task)
        if any(v.changed for k, v in result.items()):
            print(f">>> Task '{result.name.upper()}' changed...")
        if result.failed:
            print(f">>> Task '{result.name.upper()}' failed... result:")
            print_result(result)
        else:
            print(f">>> Task '{result.name.upper()}' completed successfully!")