def main():

    # Initialize Nornir object using hosts.yaml and groups.yaml
    norn = InitNornir(config_file="nornir.yml")
    nornir_set_creds(norn)

    print("Transferring files")
    result = norn.run(
        task=os_upgrade,
        num_workers=20,
    )
    std_print(result)

    # Filter to only a single device
    norn_ios = norn.filter(hostname="cisco1.twb-tech.com")

    aggr_result = norn_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 = norn_ios.run(
        netmiko_send_command,
        command_string="show run | section boot",
        num_workers=20,
    )
    std_print(result)
    continue_func()
Esempio n. 2
0
def main():
    # Initialize Nornir object using hosts.yaml and groups.yaml
    norn = InitNornir(config_file="nornir.yml")
    nornir_set_creds(norn)
    result = norn.run(
        task=os_upgrade,
        num_workers=20,
    )
    std_print(result)
def main():

    # Initialize Nornir object using hosts.yaml and groups.yaml
    norn = InitNornir(config_file="nornir.yml")
    nornir_set_creds(norn)

    print("Transferring files")
    result = norn.run(
        task=os_upgrade,
        num_workers=20,
    )
    std_print(result)

    # Filter to only a single device
    norn_ios = norn.filter(hostname="cisco1.twb-tech.com")

    aggr_result = norn_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 = norn_ios.run(
        netmiko_send_command,
        command_string="show run | section boot",
        num_workers=20,
    )
    std_print(result)
    continue_func()

    # Save the config
    result = norn_ios.run(
        netmiko_send_command,
        command_string="write mem",
    )
    std_print(result)

    # Reload
    continue_func(msg="Do you want to reload the device (y/n)? ")
    result = norn_ios.run(
        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 = norn_ios.run(
                netmiko_send_command,
                use_timing=True,
                command_string="y",
            )

    print("Devices reloaded")
Esempio n. 4
0
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)
Esempio n. 5
0
def send_napalm_commands(cmds, show_output=False, debug=False):
    """
    For a given list of commands, cmds, execute the napalm_cli method via Nornir Task
    and return a dictionary of dictionaries

    First key = device
    Secondary key(s) = show commands executed via cmds

    show_output is an optional argument which prints out the Ansible-like run output.
    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):

        nornir_instance = InitNornir(dry_run=True)

        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
        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: print(cli_result[dev_key][0].result.keys())

            for result_key in cli_result[dev_key][0].result.keys():
                output_dict.update(
                    {dev_key: cli_result[dev_key][0].result[result_key]})

        if debug:
            for k, v in output_dict.items():
                print("device: {} \toutput: {}".format(k, v))

    else:
        print(
            "ERROR! argument passed to function must be a list!  Will return empty dictionary."
        )

    if show_output: print_result(cli_result, vars=['stdout'])

    return output_dict
Esempio n. 6
0
def main():

    # Initialize Nornir object using hosts.yaml and groups.yaml
    brg = InitNornir(config_file="nornir.yml")
    nornir_set_creds(brg)
    test_file = 'test_file9.txt'

    result = brg.run(
        task=os_upgrade,
        num_workers=20,
    )
    std_print(result)
Esempio n. 7
0
def main():

    # Initialize Nornir object using hosts.yaml and groups.yaml
    brg = InitNornir(config_file="nornir.yml")
    nornir_set_creds(brg)

    print("Transferring files")
    result = brg.run(
        task=os_upgrade,
        num_workers=20,
    )
    std_print(result)

    # Filter to only a single device
    brg_ios = brg.filter(hostname="cisco1.twb-tech.com")

    # Verify the boot variable
    result = brg_ios.run(
        netmiko_send_command,
        command_string="show run | section boot",
        num_workers=20,
    )
    std_print(result)
    continue_func()

    # Save the config
    result = brg_ios.run(
        netmiko_send_command,
        command_string="write mem",
        num_workers=20,
    )
    std_print(result)

    # Reload
    continue_func(msg="Do you want to reload the device (y/n)? ")
    result = brg_ios.run(
        netmiko_send_command,
        use_timing=True,
        command_string="reload",
        num_workers=1,
    )

    # 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 = brg_ios.run(
                netmiko_send_command,
                use_timing=True,
                command_string="y",
            )

    print("Devices reloaded")
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])

                # If the vlan has no associated interfaces, the add it to the remove_vlan_list list
                if ints_in_vlan == 0:
                    remove_vlan_list.append(vlan_data[0])

        # Build a dictionary where the key is the device or host and the value the list of vlans to remove
        # This will be passed along when we build our configs
        j2_data_dict.update({dev: remove_vlan_list})

    # ====== Generate Configs
    # Execute a task "run" in the Nornir environment using our config_file Task function and pass it the customized data
    # which is required to build out a custom config for each device removing any unused vlans and adding the standard
    # vlans
    r = nornir_instance.run(task=config_to_file, arg=j2_data_dict)

    print("\n")
    # Prints abbreviated output
    print_result(r, vars=['stdout'])
Esempio n. 9
0
def main(config, getters, debug):
    nr = InitNornir(
        config_file=config,
        dry_run=False,
        num_workers=1 if debug else 20,
    )
    result = nr.run(
        name="Retrieving facts from the device",
        task=napalm_get,
        getters=getters,
    )
    print_result(
        result,
        severity_level=logging.DEBUG if debug else logging.INFO,
    )
    return result
Esempio n. 10
0
def main(config, path, debug):
    nr = InitNornir(
        config_file=config,
        dry_run=False,
        num_workers=1 if debug else 20,
    )
    result = nr.run(
        name="Backup configuration of devices",
        task=backup,
        path=path,
    )
    print_result(
        result,
        severity_level=logging.DEBUG if debug else logging.INFO,
    )
    return result
Esempio n. 11
0
def main():

    dataFile = 'expected-NOR.yml'  # expected results or new file to write results
    currentFile = 'current-NOR.yml'  # current read
    nr = InitNornir(logging_loggers=['nornir', '__main__'])

    command = 'show cdp neighbors'
    logger.info("RUNNING COMMAND %s" % command)
    start = time.time()
    result = nr.run(task=netmiko_send_command,
                    command_string=command,
                    use_textfsm=True)
    end = time.time()
    logger.info("COMMANDS RUN IN %s", str(round(end - start, 1)))

    # convert nornir output to dictionary
    current = {}
    for key in result:
        current[key] = result[key][0].result

    expected = readExpected(dataFile)
    if not expected:  # if dataFile is missing write current read to dataFile
        with open(dataFile, 'w') as dF:
            yaml.dump(current, dF, default_flow_style=False)
        dF.close()
        logger.info("EXISTING DATA MISSING - WRITTEN CURRENT TO FILE %s" %
                    dataFile)
        print("EXISTING DATA MISSING - WRITTEN CURRENT TO FILE %s" % dataFile)
    else:  # if a dataFile is present proceed with compare
        with open(currentFile, 'w') as dF:
            yaml.dump(current, dF, default_flow_style=False)
        dF.close()
        logger.info("WRITTEN CURRENT TO FILE %s" % currentFile)
        compareTopology(current, expected, nr)

    end = time.time()
    logger.info("TOTAL RUNTIME %s", str(round(end - start, 1)))
Esempio n. 12
0
def main():

    # Create Nornir instance using default hosts.yaml and groups.yaml
    print(
        "= Creating a Nornir instances which sets up a basic environment we can explore.."
    )
    nornir_instance = InitNornir()

    # print(dir(nornir_instance))
    print("\nHosts derived from the Inventory file are: \n{}".format(
        nornir_instance.inventory.hosts))
    for k, v in nornir_instance.inventory.hosts.items():
        print("\tKey: {} \tValue: {}".format(k, v))

    print("Groups derived from the Inventory file are: \n{}".format(
        nornir_instance.inventory.groups))
    for k, v in nornir_instance.inventory.groups.items():
        print("\tKey: {} \tValue: {}".format(k, v))

    print(
        '\n\n== Lets "decompose" some of these instance objects so we know what we have to work with...'
    )

    print("Decomposing Hosts object <nornir_instance.inventory.hosts>...")
    my_hosts = nornir_instance.inventory.hosts
    print("\tType of my_hosts is {}".format(type(my_hosts)))

    host_keys = list(my_hosts.keys())
    print("\tHost keys = {} of type {} ".format(host_keys, type(host_keys)))
    for i in host_keys:
        print(i)

    print("\nDecomposing Groups <nornir_instance.inventory.groups>...")
    my_groups = nornir_instance.inventory.groups
    group_keys = list(my_groups.keys())
    print("\tGroup keys = {} of type {} ".format(group_keys, type(group_keys)))
    for i in group_keys:
        print(i)

    print("\n")

    print(
        "Now that we have an environment established, lets run some discovery unsing napalm getters..."
    )
    input("Press any key to continue...")
    print(
        "We are now executing napalm get_facts on all of the hosts in our inventory."
    )

    result = nornir_instance.run(napalm_get, getters=['get_facts'])

    print("\nDecomposing Result Object of type {}...".format(type(result)))

    result_dict = dict(result)
    print(
        "Lets turn our result object into a dictionary so that now result is of type {}"
        .format(type(result_dict)))

    for i in result_dict:

        li = list(result_dict[i])

        li_keys = li[0].result['get_facts'].keys()
        # dict_keys(['uptime', 'vendor', 'os_version', 'serial_number', 'model', 'hostname', 'fqdn', 'interface_list'])
        #
        print("\n\tDecomposing Result Object for hostname {}...".format(
            li[0].result['get_facts']['hostname']))
        for k in li_keys:
            print("\t\tKey {} \t : Value = {}".format(
                k, li[0].result['get_facts'][k]))

        print("\n")

    print(
        "Print run results with the print_result module (this is an Ansible like run status)..."
    )
    print_result(result)
Esempio n. 13
0
# -*- coding: utf-8 -*-
"""
Created on Wed Feb  6 13:04:03 2019

@author: Synophic
"""
from nornir.core import InitNornir
from nornir.plugins.tasks.networking import netmiko_send_command
from nornir.plugins.functions.text import print_result

commands = input("Enter Commands: ")
cmds = commands.split(",")

for cmd in cmds:
    nr = InitNornir()

    result = nr.run(task=netmiko_send_command, command_string=cmd)

    print_result(result)
Esempio n. 14
0
#!/usr/bin/env python
"""
test
"""

from __future__ import print_function, unicode_literals
from netmiko import Netmiko
from getpass import getpass
from pprint import pprint
from nornir.core import InitNornir
from nornir.plugins.tasks import commands
from nornir.plugins.tasks.networking import netmiko_send_command
from nornir.plugins.functions.text import print_result

import pdb
import logging

nr = InitNornir()

result = nr.run(task=netmiko_send_command, command_string="show run")

print_result(result)
"""
pdb.set_trace()

result = nr.run(task=commands.remote_command, 
                command="show run")

print_result(result)
"""
### insert data into hosts yaml file
host_file = open('hosts.yaml', 'w')
host_file.write(yaml_host)
host_file.close()
############################end extracting data => yaml file ##################

print("############################################")
print("########         Runing...         #########")
print("############################################")

#############################   Main program  ##################################
nr = InitNornir()  # Initialize Nornir object using hosts.yaml and groups.yaml

nornir_set_creds(nr, sys.argv[1], sys.argv[2])  # user & password function
run_cmd1 = nr.run(task=sh_vrrp_brief, num_workers=10)  # run sh vrrp brief
run_cmd2 = nr.run(task=sh_int_loopback, num_workers=10)  # run sh int loopback
run_cmd3 = nr.run(task=sh_policy_map, num_workers=10)  # sh policy-map
run_cmd4 = nr.run(task=sh_ip_route_static,
                  num_workers=10)  # sh ip route static
run_cmd5 = nr.run(task=sh_ip_wan, num_workers=10)  # sh ip wan

copyfile('input-output/output_files/output.csv',
         'tmp/copyoutput.csv')  # copy of output.csv

with open('tmp/copyoutput.csv', newline='') as tmpfile:  #read input file
    reader = csv.reader(tmpfile)
    next(reader)  # skip_lan1 header
    for line in reader:
        name_file = line[1]
        name_file += ".txt"
Esempio n. 16
0
# Example from Patrick Ogenstad at Networklore
# https://networklore.com/introducing-nornir
# https://blogs.cisco.com/developer/nornir-python-automation-framework
from nornir.core import InitNornir
from nornir.plugins.tasks.networking import napalm_get
from nornir.plugins.functions.text import print_result

nornir_object = InitNornir()

result = nornir_object.run(
             napalm_get,
             getters=['get_facts'])

print_result(result)
Esempio n. 17
0
# https://networklore.com/introducing-nornir
# https://blogs.cisco.com/developer/nornir-python-automation-framework
from nornir.core import InitNornir
from nornir.plugins.tasks.networking import napalm_get, napalm_cli
from nornir.plugins.functions.text import print_result

nornir_instance = InitNornir(dry_run=True)

myhosts = nornir_instance.inventory.hosts['pacific-as01'].to_dict()
# print(myhosts)

# result = nornir_object.run(
#              napalm_get,
#              getters=['get_facts'])

cli_result = nornir_instance.run(napalm_cli,
                                 commands=['show vlan', 'show ver'])

print()
print("cli keys")
print(cli_result.keys())

print(cli_result['pacific-as01'])

print("result keys")
print(cli_result['pacific-as01'][0].result.keys())

# print(cli_result['pacific-as01'][0].result['show vlan'])
# print(cli_result['pacific-as01'][0].result['show ver'])
# print(len(cli_result['pacific-as01']))
# print(dir(cli_result['pacific-as01'][0]))
Esempio n. 18
0
from nornir.core import InitNornir
from nornir.plugins.tasks.networking import netmiko_file_transfer

from nornir_utilities import nornir_set_creds, std_print

# Initialize Nornir object using hosts.yaml and groups.yaml
norn = InitNornir(config_file="nornir.yml")
nornir_set_creds(norn)
test_file = 'test_file4.txt'

result = norn.run(
    task=netmiko_file_transfer,
    source_file=test_file,
    dest_file=test_file,
    direction='put',
    num_workers=20,
)
std_print(result)
Esempio n. 19
0
from nornir.core import InitNornir
from nornir.plugins.tasks.networking import napalm_get
from nornir.plugins.functions.text import print_result

nr = InitNornir()

result = nr.run(napalm_get, getters=['get_facts'])

print_result(result)
from nornir.core import InitNornir
from nornir.plugins.tasks.networking import napalm_get
from nornir.plugins.functions.text import print_result

nr = InitNornir()

result = nr.run(
              napalm_get,
              getters=['get_facts', 'get_config',])              

print_result(result)
#!/usr/bin/env python

##############################################################
# Author: Stuart Clark <*****@*****.**>
#
#
# Allows you to validate configurations to an IOS-XR device
# python
##############################################################

from nornir.core 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 interfaces")

print_result(result)