Пример #1
0
def cli(ctx, advanced_filter, f, save, **kwargs):
    """
    Do simple or advanced filtering
    that will enable us to operate on groups of hosts
    based on their properties.
    """
    try:
        ctx.obj["nornir"] = _pickle_to_hidden_file("temp.pkl", mode="rb", dump=False)
        if advanced_filter:
            ctx.obj["nornir"] = _get_obj_after_adv_filter(ctx.obj["nornir"], f)
        else:
            d = dict(
                [_json_loads(i) for i in (value.split("=") for value in _get_lists(f))]
            )
            ctx.obj["nornir"] = ctx.obj["nornir"].filter(**d)
        if save:
            _pickle_to_hidden_file("temp.pkl", obj=ctx.obj["nornir"])

        # run show_inventory command
        if any(kwargs.values()):
            ctx.invoke(cmd_show_inventory.cli, **kwargs)
    except (ValueError, IndexError):
        raise ctx.fail(
            click.BadParameter(
                f"{ERROR_MESSAGE}",
            ).format_message(),
        )
Пример #2
0
def cli(ctx, attributes, failed, severity_level, print_host, count,
        print_stat):
    """
    print_result from nornir_utils
    """

    try:
        result = ctx.obj["result"]
    except KeyError:
        raise ctx.fail(ERROR_MESSAGE)

    print_result(
        result,
        vars=_json_loads([attributes])[0],
        failed=failed,
        severity_level=getattr(logging, severity_level, 20),
        count=count,
        print_host=print_host,
    )

    # print statistic
    if print_stat:
        try:
            nr = ctx.obj["nornir"]
        except KeyError:
            nr = _pickle_to_hidden_file("temp.pkl", mode="rb", dump=False)

        ps(nr, result)
def cli(
    ctx,
    dirname,
    attributes,
    append,
    print_diff,
    diff_to_file,
    write_host,
    failed,
    severity_level,
    count,
    print_stat,
    no_errors,
):
    """
    Write an object of type `nornir.core.task.Result` to files with hostname names
    """

    try:
        result = ctx.obj["result"]
    except KeyError:
        raise ctx.fail(ERROR_MESSAGE)

    try:
        diffs = write_results(
            result,
            dirname=dirname,
            vars=_json_loads([attributes])[0],
            failed=failed,
            severity_level=getattr(logging, severity_level, 20),
            count=count,
            write_host=write_host,
            no_errors=no_errors,
            append=append,
        )

        if print_diff:
            for diff in diffs:
                print()
                print("\n\n".join(diff))
            print()

        if diff_to_file:
            Path(diff_to_file).mkdir(parents=True, exist_ok=True)
            for name, diff in diffs:
                with open(os.path.join(diff_to_file, name), mode="w") as f:
                    f.write(diff)
    except Exception as err:
        raise click.ClickException(err)

    if print_stat:
        try:
            nr = ctx.obj["nornir"]
        except KeyError:
            nr = _pickle_to_hidden_file("temp.pkl", mode="rb", dump=False)

        ps(nr, result)
Пример #4
0
def cli(ctx, pg_bar, print_result, print_stat, *args, **kwargs):
    ConnectionPluginRegister.auto_register()

    # 'None' = None
    kwargs.update({k: v for k, v in zip(kwargs, _json_loads(kwargs.values()))})

    current_func_params = next(ctx.obj["queue_functions_generator"])

    # try to pass not all arguments, but only the necessary ones
    if kwargs == list(current_func_params.values())[0]:
        function, parameters = list(current_func_params.items())[0]
    else:
        param_iterator = iter(current_func_params.values())
        params = list(next(param_iterator).items())
        function, parameters = list(current_func_params)[0], {
            key: value
            for key, value in kwargs.items() if (key, value) not in params
        }

    # get the current Nornir object from Commands chain or from temp.pkl file
    try:
        nr = ctx.obj["nornir"]
    except KeyError:
        nr = _pickle_to_hidden_file("temp.pkl", mode="rb", dump=False)

    nr.config.logging.configure()

    # pg_bar option
    if pg_bar:
        with tqdm(
                total=len(nr.inventory.hosts),
                desc="processing: ",
        ) as pb:
            result = nr.run(
                task=multiple_progress_bar,
                method=function,
                pg_bar=pb,
                **parameters,
            )
        print()
    else:
        result = nr.run(
            task=function,
            **parameters,
        )

    ctx.obj["result"] = result

    # print_result option
    if print_result:
        pr(result)
        print()

    # print statistic
    if print_stat:
        ps(nr, result)
def cli(ctx, username, password, hosts, groups, defaults, save):
    """
    Change username and password for current Nornir object.\n\n
    If no options are specified, the username and password will be changed for defaults
    only, as instance:\n
        nornir_cli nornir-scrapli change_credentials -u user -p password show_inventory -i defaults\n\n
    If only hosts or groups are specified (use string for single host and list of
    strings for many hosts), then the username and password will be
    changed only for them, as instance:\n
        nornir_cli nornir-scrapli change_credentials -u user -p password -h '["spine_1"]'\n\n
    To change the username and password for all hosts or groups, use "all" as option
    value, as instance:\n
        nornir_cli nornir-scrapli change_credentials -u user -p password -h "all"
    """
    def _change_username_or_password(item, username, password):
        if username:
            item.username = username
        if password:
            item.password = password

    try:
        nr = ctx.obj["nornir"]
    except KeyError:
        nr = _pickle_to_hidden_file("temp.pkl", mode="rb", dump=False)

    for s, k, v in zip(
        ("--hosts", "--groups"),
        (hosts, groups),
        (nr.inventory.hosts, nr.inventory.groups),
    ):
        if k == "all":
            for item in v.values():
                _change_username_or_password(item, username, password)
        elif k:
            k = _json_loads([k],
                            parameter=f"{s}",
                            typ=(str, list),
                            parameter_types="str or list")[0]
            if isinstance(k, str):
                k = [k]
            for item in k:
                try:
                    _change_username_or_password(v[item], username, password)
                except KeyError:
                    raise click.BadParameter(f"{item} does not exists")

    if defaults or not (hosts and groups and defaults):
        defaults_inv = nr.inventory.defaults

        _change_username_or_password(defaults_inv, username, password)

    ctx.obj["nornir"] = nr

    if save:
        _pickle_to_hidden_file("temp.pkl", obj=nr)
Пример #6
0
def cli(
    ctx,
    config_file,
    dry_run,
    username,
    password,
    from_dict,
    connection_options,
    **kwargs,
):
    """
    Initialize nornir with a configuration file, with code
    or with a combination of both.
    """

    ctx.ensure_object(dict)

    try:

        TransformFunctionRegister.register("adapt_host_data", adapt_host_data)

        if from_dict:
            d = dict([
                _json_loads(i)
                for i in (value.split("=") for value in _get_lists(from_dict))
            ])
            cf = (None if not config_file or config_file == "None" or "null"
                  else config_file)
            ctx.obj["nornir"] = InitNornir(config_file=cf,
                                           dry_run=dry_run,
                                           **d)
        else:
            ctx.obj["nornir"] = InitNornir(config_file=config_file,
                                           dry_run=dry_run)

        defaults = ctx.obj["nornir"].inventory.defaults

        if username:
            defaults.username = username
        if password:
            defaults.password = password

        if connection_options:
            for param in ctx.obj["nornir"].inventory.hosts.values():
                param.connection_options = connection_options

        _pickle_to_hidden_file("temp.pkl", obj=ctx.obj["nornir"])

        # run show_inventory command
        if any(kwargs.values()):
            ctx.invoke(cmd_show_inventory.cli, **kwargs)

    except (ValueError, IndexError, TypeError, KeyError):
        raise ctx.fail(
            click.BadParameter(f"{ERROR_MESSAGE}", ).format_message(), )
    except (AttributeError):
        ctx.fail(f"File '{config_file}' is empty", )
    except (FileNotFoundError):
        raise ctx.fail(
            click.BadParameter(
                f"Path '{config_file}' does not exist",
                param_hint="'--config_file' / '-c'",
            ).format_message(), )
    except Exception as err:
        raise click.ClickException(err)
Пример #7
0
def cli(ctx, pg_bar, show_result, *args, **kwargs):
    ConnectionPluginRegister.auto_register()

    # 'None' = None
    kwargs.update({k: v for k, v in zip(kwargs, _json_loads(kwargs.values()))})

    current_func_params = next(ctx.obj["queue_functions_generator"])

    # try to pass not all arguments, but only the necessary ones
    if kwargs == list(current_func_params.values())[0]:
        function, parameters = list(current_func_params.items())[0]
    else:
        param_iterator = iter(current_func_params.values())
        params = list(next(param_iterator).items())
        function, parameters = list(current_func_params)[0], {
            key: value
            for key, value in kwargs.items() if (key, value) not in params
        }

    # get the current Nornir object from Commands chain or from temp.pkl file
    try:
        nr = ctx.obj["nornir"]
    except KeyError:
        nr = _pickle_to_hidden_file("temp.pkl", mode="rb", dump=False)

    nr.config.logging.configure()

    # pg_bar option
    if pg_bar:
        with tqdm(
                total=len(nr.inventory.hosts),
                desc="processing: ",
        ) as pb:
            task = nr.run(
                task=multiple_progress_bar,
                method=function,
                pg_bar=pb,
                **parameters,
            )
        print()
    else:
        task = nr.run(
            task=function,
            **parameters,
        )

    # show_result option
    if show_result:
        print_result(task, severity_level=logging.DEBUG)
        print()

    # show statistic
    ch_sum = 0
    for host in nr.inventory.hosts:
        f, ch = (task[host].failed, task[host].changed)
        ch_sum += int(ch)
        click.secho(
            f"{host:<50}: ok={not f:<15} changed={ch:<15} failed={f:<15}",
            fg=_get_color(f, ch),
            bold=True,
        )
    print()
    f_sum = len(nr.data.failed_hosts)
    ok_sum = len(nr.inventory.hosts) - f_sum
    for state, summary, color in zip(("OK", "CHANGED", "FAILED"),
                                     (ok_sum, ch_sum, f_sum),
                                     ("green", "yellow", "red")):
        click.secho(
            f"{state:<8}: {summary}",
            fg=color,
            bold=True,
        )
    print()