Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""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
def _ParseIndex(self, preread, precompile):
"""Reads index file and stores entries in TextTable.
For optimisation reasons, a second table is created with compiled entries.
Args:
preread: func, Pre-processing, applied to each field as it is read.
precompile: func, Pre-compilation, applied to each field before compiling.
Raises:
IndexTableError: If the column headers has illegal column labels.
"""
self.index = texttable.TextTable()
self.index.CsvToTable(self._index_handle)
if preread:
for row in self.index:
for col in row.header:
row[col] = preread(col, row[col])
self.compiled = copy.deepcopy(self.index)
for row in self.compiled:
for col in row.header:
if precompile:
row[col] = precompile(col, row[col])
if row[col]:
row[col] = copyable_regex_object.CopyableRegexObject(row[col])
def _SetTable(self, table):
"""Sets table, with column headers and separators."""
if not isinstance(table, TextTable):
raise TypeError('Not an instance of TextTable.')
self.Reset()
self._table = copy.deepcopy(table._table) # pylint: disable=W0212
# Point parent table of each row back ourselves.
for row in self:
row.table = self
# Silently skip attributes not present in the index file.
# pylint: disable=E1103
if (
key in row.header
and row[key]
and not row[key].match(attributes[key])
):
# This line does not match, so break and try next row.
raise StopIteration()
return row.row
except StopIteration:
pass
return 0
class CliTable(texttable.TextTable):
"""Class that reads CLI output and parses into tabular format.
Reads an index file and uses it to map command strings to templates. It then
uses TextFSM to parse the command output (raw) into a tabular format.
The superkey is the set of columns that contain data that uniquely defines the
row, the key is the row number otherwise. This is typically gathered from the
templates 'Key' value but is extensible.
Attributes:
raw: String, Unparsed command string from device/command.
index_file: String, file where template/command mappings reside.
template_dir: String, directory where index file and templates reside.
"""
# Parse each template index only once across all instances.
# Without this, the regexes are parsed at every call to CliTable().
_lock = threading.Lock()
INDEX = {}