-
Notifications
You must be signed in to change notification settings - Fork 0
/
exp_cli.py
161 lines (108 loc) · 4.97 KB
/
exp_cli.py
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
##############################################################################################
# modules
##############################################################################################
import paramiko
import datetime
from datetime import datetime
import re
import logging
##############################################################################################
# Functions
##############################################################################################
def parse_resp_exp(func):
"""
Decorator function to parse th results of each command that is run in the server CLI.
"""
def inner(*args,**kwargs):
resp = str(func(*args,**kwargs)).replace("'b'", "").split('\\r\\n')
return resp
return inner
##############################################################################################
# Classes
##############################################################################################
class SSHConnectExp:
"""
Creates an instance of the paramiko.SSHClient() class, and opens an SSH session to the server
: param node : The hostname or IP of the UCM, IM&P or CUC server.
: param username : username of the given server.
: param password : password of the given server.
"""
def __init__(self, node, username, password):
self.node = node
self.username = username
self.password = password
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(hostname=self.node,username=self.username,password=self.password,timeout=60)
self.conn = self.client.invoke_shell()
def __repr__(self):
return f'SSHConnect("{self.node}")'
def __str__(self):
return f'SSHConnect("{self.node}")'
def init_connect(self):
"""
Method to return the initial 'OK' prompt after an SSH session is opened.
"""
logging.debug('## {} - {}.init_connect() -- ENTER'.format(__name__, self))
try:
def _init_connect(buffer=''):
prompt = False
output = self.conn.recv(65535)
buffer += str(output)
recursion_depth = 1
max_recursion_depth = 10
if 'OK' not in buffer and max_recursion_depth <= 10:
logging.debug('## {} - {}.init_connect() -- PROMPT == {}'.format(__name__, self, prompt))
recursion_depth += 1
return _init_connect(buffer)
elif 'OK' not in buffer and max_recursion_depth > 10:
raise RecursionError('Too many loops.')
elif 'OK' in buffer:
prompt = True
logging.debug('## {} - {}.init_connect() -- PROMPT == {}'.format(__name__, self, prompt))
return prompt
return _init_connect()
except Exception as e:
logging.debug('## {} - {}.init_connect() -- EXCEPTION == {}'.format(__name__, self, e))
return e
@parse_resp_exp
def run_cmd(self, cmd):
"""
Runs a CLI command on the target server and confirms the return of the 'OK' prompt before completing.
Decorated by the parse_resp() function to properly parse the return.
"""
logging.debug('## {} - {}.run_cmd() -- ENTER'.format(__name__, self))
try:
self.conn.send(cmd + '\n')
def _run_cmd(buffer=''):
prompt = False
output = self.conn.recv(65535)
buffer += str(output)
recursion_depth = 1
max_recursion_depth = 10
if 'OK' not in buffer and max_recursion_depth <= 10:
logging.debug('## {} - {}.run_cmd("{}") -- PROMPT == {}'.format(__name__, self, cmd, prompt))
return _run_cmd(buffer)
elif 'OK' not in buffer and max_recursion_depth > 10:
raise RecursionError('Too many loops.')
elif 'OK' in buffer:
prompt = True
logging.debug('## {} - {}.run_cmd("{}") -- PROMPT == {}'.format(__name__, self, cmd, prompt))
return buffer
return _run_cmd()
except Exception as e:
logging.debug('## {} - {}.run_cmd("{}") -- EXCEPTION == {}'.format(__name__, self, cmd, e))
return e
def close_ssh(self):
"""
Closes the SSH connection to the target server.
"""
self.client.close()
logging.debug('## {} - {}.close_ssh()'.format(__name__, self))
##############################################################################################
# Run
##############################################################################################
if __name__ == '__main__':
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.DEBUG, datefmt="%H:%M:%S")
pass