Ejemplo n.º 1
0
def test_obtain_all_devices():
    """Dynamically create 'all' group."""
    netmiko_tools_load = utilities.load_devices(CONFIG_FILENAME)
    expected = {
        "rtr1": {
            "device_type": "cisco_ios",
            "ip": "10.10.10.1",
            "username": "******",
            "password": "******",
            "secret": "cisco123",
        },
        "rtr2": {
            "device_type": "cisco_ios",
            "ip": "10.10.10.2",
            "username": "******",
            "password": "******",
            "secret": "cisco123",
        },
    }
    result = utilities.obtain_all_devices(netmiko_tools_load)
    assert result == expected
Ejemplo n.º 2
0
def test_obtain_all_devices():
    """Dynamically create 'all' group."""
    netmiko_tools_load = utilities.load_devices(CONFIG_FILENAME)
    expected = {
        "rtr1": {
            "device_type": "cisco_ios",
            "ip": "10.10.10.1",
            "username": "******",
            "password": "******",
            "secret": "cisco123",
        },
        "rtr2": {
            "device_type": "cisco_ios",
            "ip": "10.10.10.2",
            "username": "******",
            "password": "******",
            "secret": "cisco123",
        },
    }
    result = utilities.obtain_all_devices(netmiko_tools_load)
    assert result == expected
Ejemplo n.º 3
0
def main(args):
    start_time = datetime.now()
    cli_args = parse_arguments(args)

    cli_username = cli_args.username if cli_args.username else None
    cli_password = getpass() if cli_args.password else None
    cli_secret = getpass("Enable secret: ") if cli_args.secret else None

    version = cli_args.version
    if version:
        print("netmiko-show v{}".format(__version__))
        return 0
    list_devices = cli_args.list_devices
    if list_devices:
        my_devices = load_devices()
        display_inventory(my_devices)
        return 0

    cli_command = cli_args.cmd
    cmd_arg = False
    if cli_command:
        cmd_arg = True
    device_or_group = cli_args.devices.strip()
    pattern = r"."
    use_cached_files = cli_args.use_cache
    hide_failed = cli_args.hide_failed

    output_q = Queue()
    my_devices = load_devices()
    if device_or_group == "all":
        device_group = obtain_all_devices(my_devices)
    else:
        try:
            devicedict_or_group = my_devices[device_or_group]
            device_group = {}
            if isinstance(devicedict_or_group, list):
                for tmp_device_name in devicedict_or_group:
                    device_group[tmp_device_name] = my_devices[tmp_device_name]
            else:
                device_group[device_or_group] = devicedict_or_group
        except KeyError:
            return ("Error reading from netmiko devices file."
                    " Device or group not found: {0}".format(device_or_group))

    # Retrieve output from devices
    my_files = []
    failed_devices = []
    if not use_cached_files:
        for device_name, a_device in device_group.items():
            if cli_username:
                a_device["username"] = cli_username
            if cli_password:
                a_device["password"] = cli_password
            if cli_secret:
                a_device["secret"] = cli_secret
            if not cmd_arg:
                cli_command = SHOW_RUN_MAPPER.get(a_device["device_type"],
                                                  "show run")
            my_thread = threading.Thread(target=ssh_conn,
                                         args=(device_name, a_device,
                                               cli_command, output_q))
            my_thread.start()
        # Make sure all threads have finished
        main_thread = threading.currentThread()
        for some_thread in threading.enumerate():
            if some_thread != main_thread:
                some_thread.join()
        # Write files
        while not output_q.empty():
            my_dict = output_q.get()
            netmiko_base_dir, netmiko_full_dir = find_netmiko_dir()
            ensure_dir_exists(netmiko_base_dir)
            ensure_dir_exists(netmiko_full_dir)
            for device_name, output in my_dict.items():
                file_name = write_tmp_file(device_name, output)
                if ERROR_PATTERN not in output:
                    my_files.append(file_name)
                else:
                    failed_devices.append(device_name)
    else:
        for device_name in device_group:
            file_name = obtain_netmiko_filename(device_name)
            try:
                with open(file_name) as f:
                    output = f.read()
            except IOError:
                return "Some cache files are missing: unable to use --use-cache option."
            if ERROR_PATTERN not in output:
                my_files.append(file_name)
            else:
                failed_devices.append(device_name)

    grep_options = []
    grepx(my_files, pattern, grep_options)
    if cli_args.display_runtime:
        print("Total time: {0}".format(datetime.now() - start_time))

    if not hide_failed:
        if failed_devices:
            print("\n")
            print("-" * 20)
            print("Failed devices:")
            failed_devices.sort()
            for device_name in failed_devices:
                print("  {}".format(device_name))
            print()
    return 0
Ejemplo n.º 4
0
def main(args):
    start_time = datetime.now()
    cli_args = parse_arguments(args)

    cli_username = cli_args.username if cli_args.username else None
    cli_password = getpass() if cli_args.password else None
    cli_secret = getpass("Enable secret: ") if cli_args.secret else None

    version = cli_args.version
    if version:
        print("netmiko-cfg v{}".format(__version__))
        return 0
    list_devices = cli_args.list_devices
    if list_devices:
        my_devices = load_devices()
        display_inventory(my_devices)
        return 0

    cli_command = cli_args.cmd
    cmd_arg = False
    if cli_command:
        cmd_arg = True
        if r'\n' in cli_command:
            cli_command = cli_command.strip()
            cli_command = cli_command.split(r'\n')
    elif input:
        cmd_arg = True
        command_data = cli_args.infile.read()
        command_data = command_data.strip()
        cli_command = command_data.splitlines()
    else:
        raise ValueError("No configuration commands provided.")
    device_or_group = cli_args.devices.strip()
    pattern = r"."
    hide_failed = cli_args.hide_failed

    output_q = Queue()
    my_devices = load_devices()
    if device_or_group == 'all':
        device_group = obtain_all_devices(my_devices)
    else:
        try:
            devicedict_or_group = my_devices[device_or_group]
            device_group = {}
            if isinstance(devicedict_or_group, list):
                for tmp_device_name in devicedict_or_group:
                    device_group[tmp_device_name] = my_devices[tmp_device_name]
            else:
                device_group[device_or_group] = devicedict_or_group
        except KeyError:
            return "Error reading from netmiko devices file." \
                   " Device or group not found: {0}".format(device_or_group)

    # Retrieve output from devices
    my_files = []
    failed_devices = []
    for device_name, a_device in device_group.items():
        if cli_username:
            a_device['username'] = cli_username
        if cli_password:
            a_device['password'] = cli_password
        if cli_secret:
            a_device['secret'] = cli_secret
        if not cmd_arg:
            cli_command = SHOW_RUN_MAPPER.get(a_device['device_type'],
                                              'show run')
        my_thread = threading.Thread(target=ssh_conn,
                                     args=(device_name, a_device, cli_command,
                                           output_q))
        my_thread.start()
    # Make sure all threads have finished
    main_thread = threading.currentThread()
    for some_thread in threading.enumerate():
        if some_thread != main_thread:
            some_thread.join()
    # Write files
    while not output_q.empty():
        my_dict = output_q.get()
        netmiko_base_dir, netmiko_full_dir = find_netmiko_dir()
        ensure_dir_exists(netmiko_base_dir)
        ensure_dir_exists(netmiko_full_dir)
        for device_name, output in my_dict.items():
            file_name = write_tmp_file(device_name, output)
            if ERROR_PATTERN not in output:
                my_files.append(file_name)
            else:
                failed_devices.append(device_name)

    grep_options = []
    grepx(my_files, pattern, grep_options)
    if cli_args.display_runtime:
        print("Total time: {0}".format(datetime.now() - start_time))

    if not hide_failed:
        if failed_devices:
            print("\n")
            print("-" * 20)
            print("Failed devices:")
            failed_devices.sort()
            for device_name in failed_devices:
                print("  {}".format(device_name))
            print()
    return 0