Exemple #1
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)

    # 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()
Exemple #2
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)

    # 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")
Exemple #3
0
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 deploy_vlan(task):
    task.run(task=netmiko_send_config, config_file="chris_vlan")


results = nr.run(task=deploy_vlan)

print_title("VLANS DEPLOYED")
print_result(results)
Exemple #4
0
def main():
    #nr = InitNornir(core={"num_workers": 1})
    nr = InitNornir(config_file="./config.yaml")
    aggresult = nr.run(task=my_task)
    multiresult = aggresult['r1']
    r = multiresult[0]
Exemple #5
0
 confirm router IP addressing
 interface operational status
 ping neighbor
 if not ping
    proceed with sw diag   
 else
 if bgp
    check bgp session status
    if estab
      get received prefixes


'''

nr = InitNornir(config_file="config.yaml")

# This is temporary form to pass parameters
# In future, they will be passed from external source of truth

class initForm(FlaskForm):

    router = StringField('Router', validators=[InputRequired()])
    interface = StringField('Inteface', validators=[InputRequired()])


app = Flask(__name__)
app.config['SECRET_KEY'] = '443436456542'
Bootstrap(app)

# Ping a list of neighbors
from nornir import InitNornir
from nornir.core.filter import F
from nornir.plugins.tasks.networking import netmiko_send_config
from nornir.plugins.tasks.networking import netmiko_save_config
from nornir.plugins.functions.text import print_result

if __name__ == "__main__":

    cfg = [
        "/configure system time ntp peer 130.126.24.24",
        "/configure system time ntp peer 152.2.21.1",
    ]

    nr = InitNornir(config_file="config.yaml")
    sros = nr.filter(F(groups__contains="sros"))

    # import ipdb; ipdb.set_trace()
    agg_result = sros.run(task=netmiko_send_config, config_commands=cfg)
    print_result(agg_result)

    agg_result = sros.run(task=netmiko_save_config)
    print_result(agg_result)
Exemple #7
0
from nornir import InitNornir
from nornir_scrapli.tasks import send_command, send_interactive
from nornir.plugins.functions.text import print_result

nr = InitNornir(config_file="config.yaml")


def commit_golden(task):
    cmds = [("copy run flash:golden-commit", "Destination filename", False),
            ("\n", f"{task.host}#", False)]
    task.run(task=send_interactive, interact_events=cmds)


result = nr.run(name="Saving Golden", task=commit_golden)
print_result(result)
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(name="srx2")
    #import ipdb; ipdb.set_trace()
    agg_result = nr.run(task=failed_show_command)
    print_result(agg_result)
Exemple #9
0
def main() -> None:
    nr = InitNornir(config_file="config.yaml")
    result = nr.run(task=underlay)
    print_result(result)
Exemple #10
0
def main():
    with InitNornir(config_file="nr-config-local.yaml") as nr:
        # lisbon = nr.filter(F(groups__contains="Lisbon"))
        nr.run(gather_commands, commands=COMMANDS)
Exemple #11
0
from nornir import InitNornir
from nornir.plugins.tasks import networking
from nornir.plugins.functions.text import print_result

nr = InitNornir(config_file="config.yaml", logging={"file": "mylogs", "level": "debug"})
routers = nr.filter()
result = routers.run(task=networking.netmiko_send_command, command_string="sh ip int br")
print_result(result)
Exemple #12
0
from nornir import InitNornir
from nornir.plugins.tasks.networking import netmiko_send_command
from nornir.plugins.functions.text import print_result
nr = InitNornir("config.yaml")

results = nr.run(netmiko_send_command,
                 command_string="show interface switchport")

print_result(results)
Exemple #13
0
from nornir_napalm.plugins.tasks import napalm_get
from pyats.vlan_stp_verify import verify_vlan
from nornir.core.plugins.inventory import InventoryPluginRegister

sys.path.insert(1, '../')
from inventory_script.helpers import adapt_user_password
from nornir_utils.plugins.functions import print_result
from nornir.core.filter import F
from Nornir_Configuration.config_rollback import rollback_configuration

InventoryPluginRegister.register("user_password", adapt_user_password)

testbedfile = os.path.join('../testbed.yml')
testbed = Genie.init(testbedfile)
config_files = os.path.join('../config.yaml')
nr = InitNornir(config_files)
path = os.getcwd()


def main():
    client_access_devices = nr.filter(F(device_role__name="Access"))
    client_distribution_devices = nr.filter(
        F(device_role__name="Distribution"))
    client_core_devices = nr.filter(F(device_role__name="Core"))
    access_task = client_access_devices.run(task=verify_vlan)
    print_result(access_task)
    distribution_task = client_distribution_devices.run(task=verify_vlan)
    print_result(distribution_task)
    core_task = client_core_devices.run(task=verify_vlan)
    print_result(core_task)
    client_access_devices.run(task=config_rollback,
Exemple #14
0
from nornir import InitNornir
from nornir_utils.plugins.functions import print_result, print_title
from nornir_netmiko.tasks import netmiko_send_config, netmiko_send_command, netmiko_save_config
from nornir.core.filter import F

# Specify the config file
nr = InitNornir()


def ospf_internal(task):
    # Extracting the Router's "ID" from it's IP address
    pos = str(f"{task.host.hostname}").rfind('.')
    id = str(f"{task.host.hostname}")[pos + 1:]
    loopback_ip = "1.1.1." + str(id)

    # Router's Loopback Configuration
    loopback_commands = [
        "interface loopback0",
        "ip address " + loopback_ip + " 255.255.255.255", "ip ospf 1 area 0"
    ]
    deploy_loopback = task.run(netmiko_send_config,
                               config_commands=loopback_commands)

    # Configuration of the OSPF
    ospf_commands = ["router ospf 1", "router-id " + loopback_ip]
    deploy_ospf = task.run(netmiko_send_config, config_commands=ospf_commands)

    # General config
    deploy_general = task.run(netmiko_send_config,
                              config_file="general_config")
Exemple #15
0
import threading
import os
from xml.dom import minidom
from nornir import InitNornir
from nornir.plugins.tasks.networking import netconf_get
from rich import print

nr = InitNornir(config_file="config.yaml")
LOCK = threading.Lock()
CLEAR = "clear"

os.system(CLEAR)
def netconf_mac(task):
    mac_result = task.run(task=netconf_get, path="//config/mac-address")
    mac_resulter = mac_result.result
    mac_elements = minidom.parseString(mac_resulter).getElementsByTagName("mac-address")
    LOCK.acquire()
    print(f"[green]**** {task.host} ***********[/green]\n")
    for mac in mac_elements:
        get_parents = mac.parentNode.parentNode.parentNode
        intertag = get_parents.getElementsByTagName("name")
        for inter in intertag:
            inter_output = inter.firstChild.nodeValue
            mac_output = mac.firstChild.nodeValue
            print(f"{inter_output} Physical Address: [red]{mac_output}[/red]")
    LOCK.release()

results = nr.run(task=netconf_mac)
Exemple #16
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="nxos"))
    for host, data in nr.inventory.hosts.items():
        data.password = PASSWORD
    nr.run(task=log_send_command)
from nornir import InitNornir
from nornir.plugins.tasks import networking
from nornir.plugins.functions.text import print_result
from nornir.plugins.tasks.files import write_file
from datetime import date
import pathlib


def backup_configurations(task):
    config_dir = "config_archive"
    device_dir = config_dir + "/" + task.host.name
    pathlib.Path(config_dir).mkdir(exist_ok=True)
    pathlib.Path(device_dir).mkdir(exist_ok=True)
    r = task.run(task=networking.napalm_get, getters=["config"])
    task.run(
        task=write_file,
        content=r.result["config"]["running"],
        filename=f"" + str(device_dir) + "/" + str(date.today()) + ".txt",
    )


nr = InitNornir(config_file="/Users/stephenamaki/Dropbox/netdevops/nornir/config.yaml")

target_hosts = nr.filter(role="core")
result = target_hosts.run(name="Creating Backup Archive", task=backup_configurations)

print_result(result)
Exemple #18
0
def main():
    nr = InitNornir(config_file="config.yaml", logging={"enabled": False})
    result = nr.run(task=uptime_task)
    print_result(result)
def main():
    with InitNornir("config.yaml") as nr:
        result = nr.run(task=netmiko_send_command,
                        command_string="show version",
                        use_textfsm=True)
        print_result(result)
Exemple #20
0
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)
Exemple #21
0
from nornir import InitNornir
from nornir.core.filter import F
from pprint import pprint
nr = InitNornir()
sea_and_sfo = nr.filter(F(groups__contains="sea") | F(groups__contains="sfo"))
pprint(sea_and_sfo.inventory.hosts.keys())
                              username=username,
                              password=password,
                              hostkey_verify=False,
                              device_params={'name': 'iosxr'},
                              timeout=320)
        res = dev.dispatch(to_ele(rpc_get_bgp))
        res = to_xml(res.data)
        xml_result = remove_ns(res)
        final = parse_bgp_xml(xml_result, hostname)
        return final
    except Exception as e:
        print('Failed', e)
        raise Exception


nr = InitNornir(config_file="config.yaml", dry_run=False)

all_devices = nr.filter(F(groups__contains="peering"))

r = all_devices.run(task=get_netconf_xr)

final_panda = []

for i in r:
    if i in r.failed_hosts.keys():
        print('Fail node', i)
        continue
    else:
        #print(r[i][0].result)
        final_panda = final_panda + r[i][0].result
from nornir import InitNornir
from nornir.plugins.tasks.networking import netmiko_send_command, netmiko_send_config
from nornir.plugins.tasks.networking import napalm_get, napalm_cli
from nornir.plugins.functions.text import print_result
from nornir.core.filter import F


nr = InitNornir('nornir_config.yml')

print(nr.config.core.num_workers)
r1 = nr.inventory.hosts['DEV01']
print(r1.groups)
print(r1.username)


# result = nr.run(netmiko_send_command, command_string="show ip int br")#
# print_result(result)

#result = nr.run(netmiko_send_command, command_string="show version")#
#print_result(result)

#result = nr.run(napalm_get, getters=['get_interfaces'])
#print_result(result)

#r2 = nr.filter(name="DEV02")

#result = r2.run(netmiko_send_command, command_string="show ip int br")#
#print_result(result)

#result = nr.run(task=napalm_get, getters=["interfaces"])
#print_result(result)
Exemple #24
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(F(groups__contains="nxos"))
    agg_result = nr.run(task=render_configurations)
    print_result(agg_result)
from nornir import InitNornir
from nornir.plugins.tasks.networking import netmiko_send_command
from nornir.plugins.functions.text import print_result
import os
from twilio.rest import Client

# SMS related configuraiton
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
from_number = os.environ['TWILIO_FROM_NUM']
to_number = os.environ['TWILIO_TO_NUM']

client = Client(account_sid, auth_token)

# Route detection related configuraiton
nr = InitNornir()

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

watched_routes = ['192.168.0.13']

for device in result:
    print(device + ":")
    for output in result[device]:
        for route in watched_routes:
            if route in str(output):
                print('Nice, the route is there.')
            else:
                print('Oh no, time to troubleshoot!')
                message = client.messages \
                    .create(
Exemple #26
0
from nornir_pyez.plugins.tasks import pyez_config, pyez_diff, pyez_commit
from nornir import InitNornir
from nornir_utils.plugins.functions import print_result
from nornir.core.filter import F
import os

script_dir = os.path.dirname(os.path.realpath(__file__))

nr = InitNornir(config_file=f"{script_dir}/config.yml")

junos_devices = nr.filter(F(topo_type="PE") | F(topo_type="P"))


def rsvp_config(task):
    data = task.host.data
    net_response = task.run(task=pyez_config, template_path='/mnt/c/NornirJunos/mpls_proto.j2',
                            template_vars=data, data_format='xml', name='Config RSVP')
    if net_response:
        diff = task.run(task=pyez_diff, name='RSVP diff')
    if diff:
        task.run(task=pyez_commit, name='RSVP commit')


send_result = junos_devices.run(
    task=rsvp_config)
print_result(send_result)
Exemple #27
0
from nornir import InitNornir
from nornir.plugins.functions.text import print_result
from nornir.plugins.tasks.networking import napalm_get

nr = InitNornir(config_file="config.yaml", dry_run=True)

results = nr.run(task=napalm_get, getters=["facts", "interfaces", "arp_table"])

print_result(results)
from nornir import InitNornir
from nornir.plugins.functions.text import print_result
from nornir.plugins.tasks.networking import napalm_cli

nr = InitNornir(config_file="config.yaml")


"""def rollback_diff(task):

    diff_cmds = ["diff running-config flash:rollback-0"]

    task.run(
        name="Run diff between running config and rollback config.",
        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):
Exemple #29
0
def main():
    nr = InitNornir(config_file="config.yaml")
    nr = nr.filter(name="srx2")
    nr.run(task=junos_acl)
Exemple #30
0
from nornir import InitNornir
from nornir.core.filter import F

nr = InitNornir("config.yml")

from nornir.plugins.tasks.networking import netmiko_send_command
from nornir.plugins.functions.text import print_result

devices = nr.filter((F(hostname__contains="220")))

result = devices.run(netmiko_send_command, command_string="sh ip int brief")

print_result(result)
Exemple #31
0
from nornir import InitNornir
from nornir.plugins.tasks.text import template_file
from nornir.plugins.functions.text import print_result
from nornir.plugins.tasks import networking

nr = InitNornir(config_file='config.yaml')

hosts = nr.filter(site='home', role='cisco')

fact_result = hosts.run(task=networking.napalm_get, getters=["facts"])

int_list = fact_result['host2.dc1'][0].result['facts']['interface_list']
int_list.remove('FastEthernet0/0')
result = hosts.run(task=template_file,
                   template='jin.j2',
                   path='.',
                   interfaces=int_list,
                   title="Shutdown Interfaces")

shutitalldown = hosts.run(
    task=networking.netmiko_send_config,
    config_commands=result['host2.dc1'][0].result.replace('\n\n',
                                                          '\n').split('\n'))

print_result(shutitalldown)
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)
Exemple #33
0
# Modules
from pygnmi.client import gNMIclient
from nornir import InitNornir
from nornir.core.task import Task, Result
import logging

# User-defined tasks
def gnmi_capabilites(task: Task) -> Result:
    with gNMIclient(target=(task.host.hostname, task.host.port), username=task.host.username,
                    password=task.host.password, insecure=True) as gc:

        r = gc.capabilities()

    return Result(host=task.host, result=r)

def gnmi_get(task: Task, path) -> Result:
    with gNMIclient(target=(task.host.hostname, task.host.port), username=task.host.username,
                    password=task.host.password, insecure=True) as gc:

        r = gc.get(path=path)

    return Result(host=task.host, result=r)

# Main
if __name__ == "__main__":
    nr = InitNornir(config_file='config.yaml')
    result = nr.run(task=gnmi_capabilites)
    result2 = nr.run(task=gnmi_get, path=['openconfig-interfaces:interfaces'])

    print(result2['gNMI-EOS1'][0])
import nornir.core
from nornir import InitNornir
from nornir.plugins.tasks import commands
from nornir.plugins.functions.text import print_result
from nornir.plugins.tasks import networking


nr = InitNornir(config_file="config.yaml")

facts_test = nr.filter(site="nyc", role="leaf")

result = facts_test.run(task=networking.napalm_cli, commands=["show version"])

print_result(result)
Exemple #35
0
clear_command = "clear"
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(Fore.YELLOW + "#" * 70 + Style.RESET_ALL)
targets = input("\n" + Fore.CYAN +
                "Please enter the vendor you wish to target: " +
                Style.RESET_ALL)
os.system(clear_command)
print(Fore.YELLOW + "#" * 70 + Style.RESET_ALL)
print("\n You have selected " + Style.BRIGHT + Fore.MAGENTA + targets +
      Style.RESET_ALL)
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(",")
os.system(clear_command)
for cmd in cmds:
    nr = InitNornir()
    filtered = nr.filter(F(vendor=targets))

    result = filtered.run(task=send_command,
                          name=Fore.RED + Style.BRIGHT + "COMMAND EXECUTED: " +
                          Fore.GREEN + cmd.upper(),
                          command=cmd)

    print_result(result)