-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter_base.py
More file actions
108 lines (79 loc) · 3 KB
/
Copy pathrouter_base.py
File metadata and controls
108 lines (79 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""Base router class for network device communication."""
import textfsm
import logging
from pathlib import Path
log = logging.getLogger(__name__)
class Router_Base:
"""Base class for router/switch communication via SSH."""
def __init__(self, host, username=None, password=None, port=22, ssh_config_file=None):
"""
Initialize router connection parameters.
Args:
host: Device hostname or IP address.
username: SSH username.
password: SSH password.
port: SSH port number.
ssh_config_file: Path to SSH config file.
"""
self.host = host
self.username = username
self.password = password
self.port = port
self.ssh_config_file = ssh_config_file
self.router_connect = None
def disconnect(self):
"""Disconnect from the router."""
self.router_connect = None
def run_command(self, cmd, check_return_code=True):
"""
Execute a command on the router.
Args:
cmd: Command to execute.
check_return_code: Whether to check command exit code.
Returns:
Tuple of (success, output) where success is bool and output is str.
"""
if not check_return_code:
try:
output = self.router_connect.send_command(cmd)
return True, output
except Exception as e:
return False, str(e)
cmd_with_exit = f"{cmd}; echo $?"
try:
output = self.router_connect.send_command(cmd_with_exit)
lines = output.strip().splitlines()
exit_code = int(lines[-1])
command_output = "\n".join(lines[:-1])
if exit_code != 0:
return False, command_output
return True, command_output
except Exception as e:
return False, str(e)
def parse_with_template(self, command, template_path):
"""
Execute command and parse output using TextFSM template.
Args:
command: Command to execute.
template_path: Path to TextFSM template file.
Returns:
Tuple of (success, parsed_data) where parsed_data is list of dicts.
"""
status, output = self.run_command(command)
if not status:
return False, output
try:
template_file = Path(template_path)
if not template_file.exists():
return False, f"Template file not found: {template_path}"
with open(template_file) as f:
re_table = textfsm.TextFSM(f)
header = re_table.header
result = re_table.ParseText(output)
# Convert list of lists to list of dicts
structured_data = [
dict(zip(header, row)) for row in result
]
return True, structured_data
except Exception as e:
return False, f"TextFSM Error: {str(e)}"