コード例 #1
0
def get_config(task):
    r = task.run(task=networking.napalm_get,
        getters=["config"],
        getters_options={"config": {"retrieve":"running"}})

    result = Result(host=task.host)
    result.changed = False
    result.failed = False
    result.result = r.result
    return result
コード例 #2
0
def create_result(
    result_content: Any,
    host: str = "",
    destination: Optional[str] = None,
    failed: bool = False,
    exception: Optional[BaseException] = None,
    **kwargs: Any
) -> Result:
    result = Result(host=Host(name=host), destination=destination, **kwargs)
    result.result = result_content
    result.failed = failed
    result.exception = exception
    return result
コード例 #3
0
ファイル: c.py プロジェクト: blahu/nornir-course-2019
def add_vlan(task, vlan_id, vlan_name):
    vlan_config = [f"vlan {vlan_id}", f"name {vlan_name}"]

    if task.host.platform == 'nxos':
        show_vlan = f"show vlan id {vlan_id}"
    if task.host.platform == 'eos':
        show_vlan = f"show vlan {vlan_id}"

    r = task.run(task=networking.netmiko_send_command,
                 command_string=show_vlan,
                 use_textfsm=True)

    result = Result(host=task.host)
    result.changed = False
    result.failed = False
    result.result = f"Vlan {vlan_id} already set up correctly"

    if isinstance(r.result, str) and 'not found' in r.result:
        ### create new vlan
        task.run(task=networking.netmiko_send_config,
                 config_commands=vlan_config)
        result.changed = True
        result.result = f"Vlan {vlan_id} not found - create it from scratch"

    if isinstance(r.result, str) and 'Invalid' in r.result:
        result.failed = True
        result.result = f"Vlan {vlan_id} is invalid"

    if isinstance(r.result, list):
        ### vlan exists, check name
        current_name = r.result[0]['name']
        if current_name != vlan_name:
            ### update vlan name
            task.run(task=networking.netmiko_send_config,
                     config_commands=vlan_config)
            result.changed = True
            result.result = f"Vlan {vlan_id} - wrong name ({current_name})- updating to {vlan_name}"

    return result
コード例 #4
0
ファイル: b.py プロジェクト: blahu/nornir-course-2019
def set_config(task, config):
    r = task.run(task=networking.napalm_configure,
                 configuration=config,
                 dry_run=True)
    from pprint import pprint as pp
    pp(r)

    result = Result(host=task.host)
    result.changed = r.changed
    result.failed = r.failed
    result.result = r.result
    return r
    return result
コード例 #5
0
ファイル: print_table_result.py プロジェクト: w4h1w2/fastcli
def print_table_result(
    result: ScrapliResult,
    failed: bool = False,
    severity_level: int = logging.INFO,
    parser: str = "textfsm",
    to_dict: bool = True,
    fail_to_string: bool = False,
) -> None:
    """
    Prints the :obj:`nornir.core.task.Result` from a previous task to screen

    Arguments:
        result: from a previous task
        failed: if `True` assume the task failed
        severity_level: Print only errors with this severity level or higher
        parser: textfsm|genie -- parser to parse output with
        to_dict: output structured data in dict form instead --
        basically put k:v instead of just
            lists of lists of values for textfsm output;
            ignored if parser == "genie"
        fail_to_string: fallback to printing unstructured output
        or have tasks skipped (because
            print_result won't print empty lists which scrapli
            returns if parsing fails)

    """
    updated_agg_result = AggregatedResult(result.name)
    # breakpoint()
    console = Console()
    table = Table(
        "Hostname", "Version", "Platform", "Image ID", "Image Type",
        "Uptime", "System Image", "Compiled Date")
    for hostname, multi_result in result.items():
        updated_multi_result = MultiResult(result.name)
        for individual_result in multi_result:
            scrapli_responses = getattr(
                individual_result, "scrapli_response", None)
            if isinstance(scrapli_responses, Response):
                scrapli_responses = [scrapli_responses]
            if not scrapli_responses:
                updated_multi_result.append(individual_result)
                continue
            for scrapli_response in scrapli_responses:
                parser_method = getattr(
                    scrapli_response, f"{parser}_parse_output")
                updated_result = Result(
                    host=individual_result.host,
                    changed=individual_result.changed,
                    diff=individual_result.diff,
                    exception=individual_result.exception,
                    failed=individual_result.failed,
                    name=individual_result.name,
                    severity_level=individual_result.severity_level,
                    stderr=individual_result.stderr,
                    stdout=individual_result.stdout,
                )

                if parser == "textfsm":
                    structured_result = parser_method(to_dict=to_dict)
                else:
                    structured_result = parser_method()

                if not structured_result and fail_to_string:
                    updated_result.result = scrapli_response.result
                else:
                    updated_result.result = structured_result
                updated_multi_result.append(updated_result)
            try:
                version = structured_result['version']
                table.add_row(f'[green]{version["hostname"]}[/green]',
                              f'[blue]{version["version"]}[/blue]',
                              f'[magenta]{version["platform"]}[/magenta]',
                              f'[cyan]{version["image_id"]}[/cyan]',
                              f'[orange1]{version["image_type"]}[/orange1]',
                              f'[bright_green]{version["uptime"]}[/bright_green]',
                              f'[magenta]{version["system_image"]}[/magenta]',
                              f'[yellow]{version["compiled_date"]}[/yellow]')
            except KeyError:
                print("This command is not supported in Table format!")
        if updated_multi_result:
            updated_agg_result[hostname] = updated_multi_result  # noqa

    LOCK.acquire()
    try:
        console.print(table)
    finally:
        LOCK.release()
コード例 #6
0
def print_structured_result(
    result: ScrapliResult,
    failed: bool = False,
    severity_level: int = logging.INFO,
    parser: str = "textfsm",
    to_dict: bool = True,
    fail_to_string: bool = False,
) -> None:
    """
    Prints the :obj:`nornir.core.task.Result` from a previous task to screen

    Arguments:
        result: from a previous task
        failed: if `True` assume the task failed
        severity_level: Print only errors with this severity level or higher
        parser: textfsm|genie -- parser to parse output with
        to_dict: output structured data in dict form instead -- basically put k:v instead of just
            lists of lists of values for textfsm output; ignored if parser == "genie"
        fail_to_string: fallback to printing unstructured output or have tasks skipped (because
            print_result won't print empty lists which scrapli returns if parsing fails)

    """
    updated_agg_result = AggregatedResult(result.name)
    for hostname, multi_result in result.items():
        updated_multi_result = MultiResult(result.name)
        for individual_result in multi_result:
            scrapli_responses = getattr(individual_result, "scrapli_response",
                                        None)
            if isinstance(scrapli_responses, Response):
                scrapli_responses = [scrapli_responses]
            if not scrapli_responses:
                updated_multi_result.append(individual_result)
                continue
            for scrapli_response in scrapli_responses:
                parser_method = getattr(scrapli_response,
                                        f"{parser}_parse_output")
                updated_result = Result(
                    host=individual_result.host,
                    changed=individual_result.changed,
                    diff=individual_result.diff,
                    exception=individual_result.exception,
                    failed=individual_result.failed,
                    name=individual_result.name,
                    severity_level=individual_result.severity_level,
                    stderr=individual_result.stderr,
                    stdout=individual_result.stdout,
                )

                if parser == "textfsm":
                    structured_result = parser_method(to_dict=to_dict)
                else:
                    structured_result = parser_method()

                if not structured_result and fail_to_string:
                    updated_result.result = scrapli_response.result
                else:
                    updated_result.result = structured_result
                updated_multi_result.append(updated_result)
        if updated_multi_result:
            updated_agg_result[hostname] = updated_multi_result  # noqa

    LOCK.acquire()
    try:
        _print_result(result=updated_agg_result,
                      attrs=None,
                      failed=failed,
                      severity_level=severity_level)
    finally:
        LOCK.release()