ktbyers / netmiko

Multi-vendor library to simplify Paramiko SSH connections to network devices
MIT License
3.59k stars 1.31k forks source link

Allow textfsm templates to error if unable to parse template #3479

Closed tom0010 closed 1 month ago

tom0010 commented 2 months ago

Description of Issue/Question

We are using NTC templates with Netmiko and we have identified that some calls to devices are returning the raw_output from the device instead when trying to parse a template. We would like to have a flag to return an error if Netmiko was unable to parse the TextFSM template.

Our use case is because Netmiko is returning back the raw_output if it cannot parse, and we cannot handle this appropriately and we do not know if an error occurred.

Setup

Netmiko version

4.4.0

Netmiko device_type (if relevant to the issue)

N/A

Steps to Reproduce the Issue

Error Traceback

N/A

Relevant Python code

The issue is identified here: https://github.com/ktbyers/netmiko/blob/v4.4.0/netmiko/utilities.py#L331-L352

We would like to have an error returned back, so after Netmiko returns we can continue to process, knowing that an error occurred. Right now, our application is not getting an error but a string back, therefore it assumes this is ok. We cannot do detection on if isinstance(cmd_output, str): because we don't always use templating, show run is an example of this.

Potential fix/enhancement:

def _textfsm_parse(
    textfsm_obj: clitable.CliTable,
    raw_output: str,
    attrs: Dict[str, str],
    template_file: Optional[str] = None,
    return_error: Optional[bool] = False
) -> Union[str, List[Dict[str, str]]]:
    """Perform the actual TextFSM parsing using the CliTable object."""
    tfsm_parse: Callable[..., Any] = textfsm_obj.ParseCmd
    structured_data = [] # set default empty list outside of try for the exception
    try:
        # Parse output through template
        if template_file is not None:
            tfsm_parse(raw_output, templates=template_file)
        else:
            tfsm_parse(raw_output, attrs)

        structured_data = clitable_to_dict(textfsm_obj)
        if structured_data == [] and return_error is True:
            return structured_data
        elif structured_data == [] and return_error is False:
            return raw_output
        return structured_data
    except (FileNotFoundError, CliTableError) as exception:
        if return_error is True:
            return exception
        return raw_output

This proposal would not change the current behaviour.

tom0010 commented 2 months ago

Similar to https://github.com/ktbyers/netmiko/issues/2663 and https://github.com/ktbyers/netmiko/issues/1770 which were closed and not actioned on.

tbotnz commented 2 months ago

This would be handy for sure

tom0010 commented 2 months ago

Looks like https://github.com/ktbyers/netmiko/pull/3406/files will fix this.

tom0010 commented 1 month ago

Fixed by: https://github.com/ktbyers/netmiko/pull/3494