示例#1
0
def test_invalid_netmiko_dir():
    """Try with an invalid netmiko_base_dir"""
    environ["NETMIKO_DIR"] = "/"
    try:
        utilities.find_netmiko_dir()
    except ValueError as exc:
        assert isinstance(exc, ValueError)
        return
    assert False
示例#2
0
def test_invalid_netmiko_dir():
    """Try with an invalid netmiko_base_dir"""
    os.environ["NETMIKO_DIR"] = "/"
    try:
        utilities.find_netmiko_dir()
    except ValueError as exc:
        assert isinstance(exc, ValueError)
        return
    assert False
示例#3
0
def test_find_netmiko_dir():
    """Try to get the netmiko_dir"""
    folder = dirname(__file__)
    os.environ["NETMIKO_DIR"] = folder
    result = utilities.find_netmiko_dir()
    assert result[0] == folder
    assert result[1].endswith("/tmp")
示例#4
0
def test_find_netmiko_dir():
    """Try to get the netmiko_dir"""
    folder = dirname(__file__)
    environ["NETMIKO_DIR"] = folder
    result = utilities.find_netmiko_dir()
    assert result[0] == folder
    assert result[1].endswith("/tmp")
def test_use_cache_missing_file():
    """Test use_cache with a missing cache file. Should generate error."""
    # Generate cached files
    cmd_list = [NETMIKO_GREP] + ['interface', 'all']
    _, full_dir = find_netmiko_dir()
    remove_file = 'bad_device.txt'
    remove_file_full = "{}/{}".format(full_dir, remove_file)
    if os.path.exists(remove_file_full) and os.path.isfile(remove_file_full):
        os.remove(remove_file_full)
    cmd_list = [NETMIKO_GREP] + ['--use-cache', '--display-runtime', 'interface', 'all']
    (output, std_err) = subprocess_handler(cmd_list)
    assert "Some cache files are missing: unable to use --use-cache option." in std_err
示例#6
0
def test_use_cache_missing_file():
    """Test use_cache with a missing cache file. Should generate error."""
    # Generate cached files
    cmd_list = [NETMIKO_GREP] + ['interface', 'all']
    _, full_dir = find_netmiko_dir()
    remove_file = 'bad_device.txt'
    remove_file_full = "{}/{}".format(full_dir, remove_file)
    if os.path.exists(remove_file_full) and os.path.isfile(remove_file_full):
        os.remove(remove_file_full)
    cmd_list = [NETMIKO_GREP
                ] + ['--use-cache', '--display-runtime', 'interface', 'all']
    (output, std_err) = subprocess_handler(cmd_list)
    assert "Some cache files are missing: unable to use --use-cache option." in std_err
示例#7
0
def grepx(files, pattern, grep_options, use_colors=True):
    """Call system grep"""
    if not isinstance(files, (list, tuple)):
        files = [files]
    if use_colors:
        grep_options += ["--color=auto"]

    # Make grep output look nicer by 'cd netmiko_full_dir'
    _, netmiko_full_dir = find_netmiko_dir()
    os.chdir(netmiko_full_dir)
    # Convert files to strip off the directory
    retrieve_file = lambda x: x.split("/")[-1]  # noqa
    files = [retrieve_file(a_file) for a_file in files]
    files.sort()
    grep_list = [GREP] + grep_options + [pattern] + files
    proc = subprocess.Popen(grep_list, shell=False)
    proc.communicate()
    return ""
示例#8
0
def test_obtain_netmiko_filename():
    """Test file name and that directory is created."""
    create_dir_test = True
    file_name_test = '/home/gituser/.netmiko/tmp/test_device.txt'
    file_name = obtain_netmiko_filename('test_device')
    assert file_name == file_name_test

    if create_dir_test:
        uuid_str = str(uuid.uuid1())
        junk_dir_base = '/home/gituser/JUNK/netmiko'
        junk_dir = '{}/{}'.format(junk_dir_base, uuid_str)
        base_dir, full_dir = find_netmiko_dir()
        print(base_dir)

        # Move base_dir and recreate it
        if os.path.isdir(base_dir) and os.path.isdir(junk_dir_base):
            shutil.move(src=base_dir, dst=junk_dir)
        assert os.path.exists(base_dir) == False
        assert os.path.exists(full_dir) == False
        file_name = obtain_netmiko_filename('test_device')
        ensure_dir_exists(base_dir)
        ensure_dir_exists(full_dir)
        assert os.path.exists(base_dir) == True
        assert os.path.exists(full_dir) == True
def test_obtain_netmiko_filename():
    """Test file name and that directory is created."""
    create_dir_test = True
    file_name_test = '/home/gituser/.netmiko/tmp/test_device.txt'
    file_name = obtain_netmiko_filename('test_device')
    assert file_name == file_name_test

    if create_dir_test:
        uuid_str = str(uuid.uuid1())
        junk_dir_base = '/home/gituser/JUNK/netmiko'
        junk_dir = '{}/{}'.format(junk_dir_base, uuid_str)
        base_dir, full_dir = find_netmiko_dir()
        print(base_dir)

        # Move base_dir and recreate it
        if os.path.isdir(base_dir) and os.path.isdir(junk_dir_base):
            shutil.move(src=base_dir, dst=junk_dir)
        assert os.path.exists(base_dir) == False
        assert os.path.exists(full_dir) == False
        file_name = obtain_netmiko_filename('test_device')
        ensure_dir_exists(base_dir)
        ensure_dir_exists(full_dir)
        assert os.path.exists(base_dir) == True
        assert os.path.exists(full_dir) == True
示例#10
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
示例#11
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
示例#12
0
def test_find_netmiko_dir():
    """Test function that finds netmiko_dir."""
    base_dir_check = '/home/gituser/.netmiko'
    full_dir_check = '/home/gituser/.netmiko/tmp'
    base_dir, full_dir = find_netmiko_dir()
    assert base_dir == base_dir_check and full_dir == full_dir_check
示例#13
0
def test_find_netmiko_dir():
    """Test function that finds netmiko_dir."""
    base_dir_check = '/home/gituser/.netmiko'
    full_dir_check = '/home/gituser/.netmiko/tmp'
    base_dir, full_dir = find_netmiko_dir()
    assert base_dir == base_dir_check and full_dir == full_dir_check