How to use the textfsm.TextFSM function in textfsm

To help you get started, we’ve selected a few textfsm examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ansible-network / cisco_ios / action_plugins / parse_validate_acl.py View on Github external
def _parse_acl_with_textfsm(self, parser_file, output):
        import textfsm
        tmp = open(parser_file)
        re_table = textfsm.TextFSM(tmp)
        results = re_table.ParseText(output)
        fsm_results = []
        for item in results:
            facts = {}
            facts.update(dict(zip(re_table.header, item)))
            fsm_results.append(facts)

        pd = []
        parsed_acl = []
        # Convert dictionary of terms into flows dictionary
        for term in fsm_results:
            pd_it = {}
            original_terms = {}
            for k, v in term.items():
                if k == 'LINE_NUM' and v == '':
                    # Empty line with just name
github ktbyers / pyplus_course / class4 / collateral / textfsm_simple.py View on Github external
from pprint import pprint
import textfsm

template_file = "show_ip_int_brief.template"
template = open(template_file)

with open("show_ip_int_brief.txt") as f:
    raw_text_data = f.read()

# The argument 'template' is a file handle and 'raw_text_data' is a string.
re_table = textfsm.TextFSM(template)
data = re_table.ParseText(raw_text_data)
template.close()

print("\nPrint the header row which could be used for dictionary construction")
print(re_table.header)
print("\nOutput Data: ")
pprint(data)
print()
github ktbyers / netmiko / netmiko / _textfsm / _clitable.py View on Github external
def _ParseCmdItem(self, cmd_input, template_file=None):
        """Creates Texttable with output of command.
    Args:
      cmd_input: String, Device response.
      template_file: File object, template to parse with.
    Returns:
      TextTable containing command output.
    Raises:
      CliTableError: A template was not found for the given command.
    """
        # Build FSM machine from the template.
        fsm = textfsm.TextFSM(template_file)
        if not self._keys:
            self._keys = set(fsm.GetValuesByAttrib("Key"))

        # Pass raw data through FSM.
        table = texttable.TextTable()
        table.header = fsm.header

        # Fill TextTable from record entries.
        for record in fsm.ParseText(cmd_input):
            table.Append(record)
        return table
github cldeluna / nornir-config / nornir_discovery.py View on Github external
def parse_with_texfsm(content, template_file, debug=False):

    """
    Generic TextFSM Parsing Function
    Given some content (already loaded in memory) and a TextFSM Template file, the content will be parsed and the
    output returned.

    :param content:
    :param template_file:
    :param debug:
    :return: results
    """

    template = open(template_file)

    result_of_template = textfsm.TextFSM(template)

    results = result_of_template.ParseText(content)

    if debug:
        print("\nKeys available when using the {} template:".format(template_file))
        # This shows the "column headers" or fields names of the data we will get back from ParseText
        print(result_of_template.header)
        # This shows the field names and the REGEXP that is being used to pluck out the values
        print(result_of_template.value_map)
        print("\nDetails on the results variable...")
        print("results is of type {}".format(type(results)))
        print("results has {} element(s)".format(len(results)))
        if isinstance(results, list):
            for line in results:
                print(line)
        else:
github sk2 / autonetkit / autonetkit / collection / process.py View on Github external
def process_textfsm(template_file, data):
    """
    TODO: make template return data other than just hops, and have reverse_map_path() handle accordingly
    """
    import textfsm
    with open(template_file, "r") as template:
        re_table = textfsm.TextFSM(template)

    data = re_table.ParseText(data)
    header = re_table.header
    return header, data
github napalm-automation / napalm / napalm / base / helpers.py View on Github external
for c in cls.__class__.mro():
        if c is object:
            continue
        current_dir = os.path.dirname(
            os.path.abspath(sys.modules[c.__module__].__file__)
        )
        template_dir_path = "{current_dir}/utils/textfsm_templates".format(
            current_dir=current_dir
        )
        template_path = "{template_dir_path}/{template_name}.tpl".format(
            template_dir_path=template_dir_path, template_name=template_name
        )

        try:
            with open(template_path) as f:
                fsm_handler = textfsm.TextFSM(f)

                for obj in fsm_handler.ParseText(raw_text):
                    entry = {}
                    for index, entry_value in enumerate(obj):
                        entry[fsm_handler.header[index].lower()] = entry_value
                    textfsm_data.append(entry)

                return textfsm_data
        except IOError:  # Template not present in this class
            continue  # Continue up the MRO
        except textfsm.TextFSMTemplateError as tfte:
            raise napalm.base.exceptions.TemplateRenderException(
                "Wrong format of TextFSM template {template_name}: {error}".format(
                    template_name=template_name, error=str(tfte)
                )
            )
github google / textfsm / textfsm / clitable.py View on Github external
def _ParseCmdItem(self, cmd_input, template_file=None):
    """Creates Texttable with output of command.

    Args:
      cmd_input: String, Device response.
      template_file: File object, template to parse with.

    Returns:
      TextTable containing command output.

    Raises:
      CliTableError: A template was not found for the given command.
    """
    # Build FSM machine from the template.
    fsm = textfsm.TextFSM(template_file)
    if not self._keys:
      self._keys = set(fsm.GetValuesByAttrib('Key'))

    # Pass raw data through FSM.
    table = texttable.TextTable()
    table.header = fsm.header

    # Fill TextTable from record entries.
    for record in fsm.ParseText(cmd_input):
      table.Append(record)
    return table