How to use textfsm - 10 common examples

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 google / textfsm / textfsm / texttable.py View on Github external
Raises:
      TableError: If col_size is too small to fit the words in the text.
    """
    result = []
    if '\n' in text:
      for paragraph in text.split('\n'):
        result.extend(self._TextJustify(paragraph, col_size))
      return result

    wrapper = textwrap.TextWrapper(width=col_size-2, break_long_words=False,
                                   expand_tabs=False)
    try:
      text_list = wrapper.wrap(text)
    except ValueError:
      raise TableError('Field too small (minimum width: 3)')

    if not text_list:
      return [' '*col_size]

    for current_line in text_list:
      stripped_len = len(terminal.StripAnsiText(current_line))
      ansi_color_adds = len(current_line) - stripped_len
      # +2 for white space on either side.
      if stripped_len + 2 > col_size:
        raise TableError('String contains words that do not fit in column.')

      result.append(' %-*s' % (col_size - 1 + ansi_color_adds, current_line))

    return result
github google / textfsm / textfsm / texttable.py View on Github external
if header:
      line = buf.readline()
      header_str = ''
      while not header_str:
        # Remove comments.
        header_str = line.split('#')[0].strip()
        if not header_str:
          line = buf.readline()

      header_list = header_str.split(separator)
      header_length = len(header_list)

      for entry in header_list:
        entry = entry.strip()
        if entry in header_row:
          raise TableError('Duplicate header entry %r.' % entry)

        header_row[entry] = entry
      header_row.row = 0
      self._table[0] = header_row

    # xreadlines would be better but not supported by StringIO for testing.
    for line in buf:
      # Support commented lines, provide '#' is first character of line.
      if line.startswith('#'):
        continue

      lst = line.split(separator)
      lst = [l.strip() for l in lst]
      if header and len(lst) != header_length:
        # Silently drop illegal line entries
        continue
github google / textfsm / textfsm / texttable.py View on Github external
for paragraph in text.split('\n'):
        result.extend(self._TextJustify(paragraph, col_size))
      return result

    wrapper = textwrap.TextWrapper(width=col_size-2, break_long_words=False,
                                   expand_tabs=False)
    try:
      text_list = wrapper.wrap(text)
    except ValueError:
      raise TableError('Field too small (minimum width: 3)')

    if not text_list:
      return [' '*col_size]

    for current_line in text_list:
      stripped_len = len(terminal.StripAnsiText(current_line))
      ansi_color_adds = len(current_line) - stripped_len
      # +2 for white space on either side.
      if stripped_len + 2 > col_size:
        raise TableError('String contains words that do not fit in column.')

      result.append(' %-*s' % (col_size - 1 + ansi_color_adds, current_line))

    return result
github google / textfsm / textfsm / texttable.py View on Github external
def _SmallestColSize(self, text):
    """Finds the largest indivisible word of a string.

    ...and thus the smallest possible column width that can contain that
    word unsplit over rows.

    Args:
      text: A string of text potentially consisting of words.

    Returns:
      Integer size of the largest single word in the text.
    """
    if not text:
      return 0
    stripped = terminal.StripAnsiText(text)
    return max(len(word) for word in stripped.split())
github google / textfsm / textfsm / parser.py View on Github external
if ref_table != result:
      print('Data mis-match!')
      return 1
    else:
      print('Data match!')


if __name__ == '__main__':
  help_msg = '%s [--help] template [input_file [output_file]]\n' % sys.argv[0]
  try:
    sys.exit(main())
  except Usage as err:
    print(err, file=sys.stderr)
    print('For help use --help', file=sys.stderr)
    sys.exit(2)
  except (IOError, TextFSMError, TextFSMTemplateError) as err:
    print(err, file=sys.stderr)
    sys.exit(2)
github google / textfsm / textfsm / parser.py View on Github external
# Exit value indicates if processed data matched expected result.
    with open(args[2], 'r') as f:
      ref_table = f.read()

    if ref_table != result:
      print('Data mis-match!')
      return 1
    else:
      print('Data match!')


if __name__ == '__main__':
  help_msg = '%s [--help] template [input_file [output_file]]\n' % sys.argv[0]
  try:
    sys.exit(main())
  except Usage as err:
    print(err, file=sys.stderr)
    print('For help use --help', file=sys.stderr)
    sys.exit(2)
  except (IOError, TextFSMError, TextFSMTemplateError) as err:
    print(err, file=sys.stderr)
    sys.exit(2)
github google / textfsm / textfsm / terminal.py View on Github external
# Page text supplied in either specified file or stdin.

  if len(args) == 1:
    with open(args[0], 'r') as f:
      fd = f.read()
  else:
    fd = sys.stdin.read()
  Pager(fd, delay=isdelay).Page()


if __name__ == '__main__':
  help_msg = '%s [--help] [--size] [--nodelay] [input_file]\n' % sys.argv[0]
  try:
    sys.exit(main())
  except Usage as err:
    print(err, file=sys.stderr)
    print('For help use --help', file=sys.stderr)
    sys.exit(2)
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