0
# CLI Table Management
1
2
The CLI table functionality provides automated template selection and parsing for network device command outputs. It uses index files to map TextFSM templates to specific device types and commands, enabling automated parsing of CLI data without manual template selection.
3
4
## Core Imports
5
6
```python
7
from textfsm import clitable
8
from textfsm.clitable import CliTable, IndexTable
9
from textfsm.clitable import CliTableError, IndexTableError
10
```
11
12
## Capabilities
13
14
### CliTable Parser
15
16
Automated CLI data parser that uses index files to select appropriate templates based on device attributes and command patterns.
17
18
```python { .api }
19
class CliTable(texttable.TextTable):
20
def __init__(self, index_file=None, template_dir=None):
21
"""
22
Initialize CLI table parser.
23
24
Args:
25
index_file (str): Path to index file mapping templates to devices/commands
26
template_dir (str): Directory containing TextFSM template files
27
"""
28
29
def ParseCmd(self, cmd_input, attributes=None, templates=None):
30
"""
31
Parse command output using automatic template selection.
32
33
Args:
34
cmd_input (str): Raw command output text to parse
35
attributes (dict): Device attributes for template matching
36
(e.g., {'Platform': 'cisco_ios', 'Command': 'show version'})
37
templates (list): Specific template files to use (optional)
38
39
Returns:
40
bool: True if parsing successful, False otherwise
41
"""
42
43
def AddKeys(self, keys):
44
"""
45
Add key fields to the table structure.
46
47
Args:
48
keys (list): List of key field names
49
"""
50
51
def ReadIndex(self, index_file=None):
52
"""
53
Read template index file.
54
55
Args:
56
index_file (str): Path to index file (optional)
57
"""
58
59
def sort(self, cmp=None, key=None, reverse=False):
60
"""
61
Sort table rows.
62
63
Args:
64
cmp: Comparison function (deprecated)
65
key: Key function for sorting
66
reverse (bool): Sort in reverse order
67
"""
68
69
def KeyValue(self, row=None):
70
"""
71
Get key values for a row.
72
73
Args:
74
row: Row to get keys from (default: current row)
75
76
Returns:
77
list: List of key field values
78
"""
79
80
def LabelValueTable(self, keys=None):
81
"""
82
Format table as label-value pairs.
83
84
Args:
85
keys (list): Keys to include (optional)
86
87
Returns:
88
str: Formatted label-value table
89
"""
90
91
@property
92
def index_table(self):
93
"""IndexTable object containing template mappings."""
94
95
@property
96
def template_dir(self):
97
"""Directory path containing template files."""
98
99
@property
100
def raw(self):
101
"""Raw unparsed command output."""
102
103
@property
104
def superkey(self):
105
"""Combined key for table identification."""
106
```
107
108
### Index Table Management
109
110
Manages index files that define mappings between device attributes, commands, and TextFSM template files.
111
112
```python { .api }
113
class IndexTable(object):
114
def __init__(self, preread=None, precompile=None, file_path=None):
115
"""
116
Initialize index table from file or data.
117
118
Args:
119
preread: Pre-read data for index
120
precompile: Pre-compile regex patterns
121
file_path (str): Path to index file
122
"""
123
124
def GetRowMatch(self, attributes):
125
"""
126
Find index rows matching specified criteria.
127
128
Args:
129
attributes (dict): Attribute key-value pairs to match
130
(e.g., {'Platform': 'cisco_ios', 'Command': 'show version'})
131
132
Returns:
133
int: Index of first matching row, or -1 if not found
134
"""
135
136
def __del__(self):
137
"""Destructor."""
138
139
def __len__(self):
140
"""
141
Get number of rows in index.
142
143
Returns:
144
int: Number of rows
145
"""
146
147
def __copy__(self):
148
"""Create shallow copy."""
149
150
def __deepcopy__(self, memodict=None):
151
"""Create deep copy."""
152
153
@property
154
def header(self):
155
"""List of column headers."""
156
157
@property
158
def index(self):
159
"""List of index rows."""
160
161
@property
162
def compiled(self):
163
"""Compiled regex patterns for matching."""
164
```
165
166
## Usage Examples
167
168
### Basic CLI Table Usage
169
170
```python
171
from textfsm import clitable
172
173
# Initialize with index file and template directory
174
cli_table = clitable.CliTable('index.csv', 'templates/')
175
176
# Parse command output with device attributes
177
attributes = {
178
'Platform': 'cisco_ios',
179
'Command': 'show version'
180
}
181
182
cmd_output = """
183
Cisco IOS Software, C2900 Software (C2900-UNIVERSALK9-M), Version 15.1(4)M5
184
Router uptime is 5 days, 14 hours, 23 minutes
185
"""
186
187
success = cli_table.ParseCmd(cmd_output, attributes)
188
if success:
189
print(cli_table.FormattedTable())
190
```
191
192
### Working with Index Tables
193
194
```python
195
from textfsm import clitable
196
197
# Create index table
198
index = clitable.IndexTable()
199
200
# Add mappings
201
index.AddRow(['cisco_ios', 'show version', 'cisco_ios_show_version.textfsm'])
202
index.AddRow(['cisco_ios', 'show interfaces', 'cisco_ios_show_interfaces.textfsm'])
203
204
# Find matching templates
205
matches = index.GetRowMatch(Platform='cisco_ios', Command='show version')
206
print(matches) # Returns matching rows
207
```
208
209
### Index File Format
210
211
Index files are CSV format with columns defining device attributes and template mappings:
212
213
```csv
214
Platform,Command,Template
215
cisco_ios,show version,cisco_ios_show_version.textfsm
216
cisco_ios,show interfaces,cisco_ios_show_interfaces.textfsm
217
cisco_nxos,show version,cisco_nxos_show_version.textfsm
218
juniper_junos,show version,juniper_junos_show_version.textfsm
219
```
220
221
### Custom Attribute Matching
222
223
```python
224
# Use custom attributes for template selection
225
custom_attributes = {
226
'Platform': 'cisco_ios',
227
'Command': 'show ip route',
228
'Version': '15.1',
229
'Model': 'C2900'
230
}
231
232
cli_table = clitable.CliTable('advanced_index.csv', 'templates/')
233
success = cli_table.ParseCmd(route_output, custom_attributes)
234
```
235
236
### Error Handling
237
238
```python
239
from textfsm import clitable
240
241
try:
242
cli_table = clitable.CliTable('index.csv', 'templates/')
243
success = cli_table.ParseCmd(cmd_output, attributes)
244
245
if not success:
246
print("No matching template found or parsing failed")
247
else:
248
# Process results
249
for row in cli_table:
250
print(row)
251
252
except clitable.CliTableError as e:
253
print(f"CLI table error: {e}")
254
except clitable.IndexTableError as e:
255
print(f"Index table error: {e}")
256
```