-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSSHConnettors.py
More file actions
391 lines (355 loc) · 16.2 KB
/
Copy pathSSHConnettors.py
File metadata and controls
391 lines (355 loc) · 16.2 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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
from builtins import print
import pexpect
import re
from NetworkElements import Switch
from NetworkElements import Port
import os
class CiscoSSH:
def __init__(self, c_interface, m_timeout):
self.connected_interface = c_interface
self.monitor_timeout = m_timeout
self.switch_interfaces = list()
self.child = None
self.switch = None
def connect(self, ip, name, pwd, en_pwd, max_attempts=1):
attempts = 0
while attempts < max_attempts:
try:
self.child = pexpect.spawn("ssh %s@%s" % (name, ip))
self.child.timeout = 15
self.child.expect('Password:')
self.child.sendline(pwd)
self.child.expect('>')
self.child.sendline('terminal length 0')
self.child.expect('>')
self.child.sendline('enable')
self.child.expect('Password:')
self.child.sendline(en_pwd)
self.child.expect('%s#' % name)
print("Connected!")
self.switch = Switch(name, ip, pwd, en_pwd, self.connected_interface)
return True
except (pexpect.EOF, pexpect.TIMEOUT):
if "Password" in str(self.child.before):
print("Wrong Credentials..")
return False
if "Host key verification failed." in str(self.child.before):
print("Host key verification failed. Retring!")
os.system('ssh-keygen -f "/root/.ssh/known_hosts" -R %s' % ip)
return self.connect_with_no_host_auth(ip, name, pwd, en_pwd)
if "The authenticity of host" in str(self.child.before):
return self.connect_with_no_host_auth(ip, name, pwd, en_pwd)
if attempts < max_attempts:
print("Attempt #%s failed! i'm triyng again!" % attempts)
else:
print("\n\n>>>>>>>>>>>CONNECTION ERROR<<<<<<<<<<<\n\n")
return False
self.child.close()
attempts += 1
def connect_with_no_host_auth(self, ip, name, pwd, en_pwd):
print("I'm trying to acknowledge the authenticity of the new host")
try:
self.child = pexpect.spawn("ssh %s@%s" % (name, ip))
self.child.expect('The authenticity of host')
self.child.sendline('yes')
self.child.expect('Password:')
self.child.sendline(pwd)
self.child.expect('>')
self.child.sendline('terminal length 0')
self.child.expect('>')
self.child.sendline('enable')
self.child.expect('Password:')
self.child.sendline(en_pwd)
self.child.expect('%s#' % name)
print("Connected!")
self.switch = Switch(name, ip, pwd, en_pwd, self.connected_interface)
return True
except (pexpect.EOF, pexpect.TIMEOUT):
print("\n\n>>>>>>>>>>>CONNECTION ERROR<<<<<<<<<<<\n\n")
self.child.close()
return False
def reconnect(self, ip, name, pwd, en_pwd, c_interface, m_timeout):
self.connected_interface = c_interface
self.monitor_timeout = m_timeout
self.connect(ip, name, pwd, en_pwd, 20)
def take_interfaces(self):
self.child.sendline('show interfaces | i (.* line protocol is )|(.* address is)')
self.child.expect('%s#' % self.switch.name)
output = str(self.child.before)
raw_port_name = re.findall('([^\\n]\w*[^0-9]\d\/\d\.*\d*)', output)
raw_port_mac = re.findall('([a-fA-F0-9]{4}[.][a-fA-F0-9]{4}[.][a-fA-F0-9]{4})[^\)]', output)
if len(raw_port_mac) == len(raw_port_name):
dim = len(raw_port_name)
else:
if len(raw_port_mac) < len(raw_port_name):
dim = len(raw_port_mac)
else:
dim = len(raw_port_name)
for i in range(dim):
name = raw_port_name[i].lstrip('\\n')
mac_parts = raw_port_mac[i].split('.')
mac = mac_parts[0][:2] + ':' + mac_parts[0][2:4] + ':' + mac_parts[1][:2] + ':' + \
mac_parts[1][2:4] + ':' + mac_parts[2][:2] + ':' + mac_parts[2][2:4]
self.switch.add_ports(Port(name, mac))
if name not in self.switch_interfaces:
self.switch_interfaces.append(name)
return self.switch
def put_callback(self):
print("I'm trying to enable the callback")
self.child.sendline('configure terminal')
self.child.expect('\(config\)#')
self.child.sendline('event manager applet no-monitor-session')
self.child.expect('\(config-applet\)#')
self.child.sendline('event timer countdown time %s' % self.monitor_timeout)
self.child.expect('\(config-applet\)#')
self.child.sendline('action 01 cli command "enable"')
self.child.expect('\(config-applet\)#')
self.child.sendline('action 02 cli command "configure terminal"')
self.child.expect('\(config-applet\)#')
self.child.sendline('action 03 cli command "no monitor session 27"')
self.child.expect('\(config-applet\)#')
self.child.sendline('action 04 cli command "end"')
self.child.expect('\(config-applet\)#')
self.child.sendline('action 05 cli command "exit"')
self.child.expect('\(config-applet\)#')
self.child.sendline('end')
self.child.expect('%s#' % self.switch.name)
print("Finished!")
def enable_monitor_mode(self):
try:
self.clear_vty_line()
self.put_callback()
print("Enabling monitor mode...")
self.child.sendline('configure terminal')
self.child.expect('\(config\)#')
for interface in self.switch_interfaces:
if self.connected_interface[-3:] not in interface:
self.child.sendline('monitor session 27 source interface %s' % interface)
self.child.expect('\(config\)#')
self.child.sendline(
'monitor session 27 destination interface %s encapsulation replicate' % self.connected_interface)
self.child.expect('\(config\)#')
self.child.close()
except (pexpect.EOF, pexpect.TIMEOUT):
print("Connection Closed!")
def enable_monitor_mode_on_interface_range(self, interfaces):
try:
self.clear_vty_line()
self.put_callback()
print("Enabling monitor mode...")
self.child.sendline('configure terminal')
self.child.expect('\(config\)#')
for interface in interfaces:
if self.connected_interface[-3:] not in interface:
self.child.sendline('monitor session 27 source interface %s' % interface)
self.child.expect('\(config\)#')
self.child.sendline(
'monitor session 27 destination interface %s encapsulation replicate' % self.connected_interface)
self.child.expect('\(config\)#')
except (pexpect.EOF, pexpect.TIMEOUT):
print("Connection Closed!")
self.child.close()
def enable_monitor_mode_on_specific_port(self, port_name):
try:
self.clear_vty_line()
self.put_callback()
print("Enabling monitor mode...")
self.child.timeout = 5
self.child.sendline('configure terminal')
self.child.expect('\(config\)#')
self.child.sendline('monitor session 27 source interface %s' % port_name)
self.child.expect('\(config\)#')
self.child.sendline(
'monitor session 27 destination interface %s encapsulation replicate' % self.connected_interface)
self.child.expect('\(config\)#')
except (pexpect.EOF, pexpect.TIMEOUT):
print("Connection Closed!")
self.child.close()
def clear_vty_line(self):
print("Clearing vty lines")
for i in range(5):
self.child.sendline('clear line vty %s' % i)
self.child.expect('[confirm]')
self.child.sendline('\n')
self.child.expect('%s#' % self.switch.name)
print("Done!")
class ExtremeSSH:
def __init__(self, c_interface, m_timeout, switch_mac):
self.connected_interface = c_interface
self.vlan = 3
self.switch_mac = switch_mac
self.monitor_timeout = m_timeout
self.switch_interfaces = list()
self.child = None
self.switch = None
def connect(self, ip, name, pwd, en_pwd, max_attempts=1):
attempts = 0
while attempts < max_attempts:
try:
self.child = pexpect.spawn("ssh %s@%s" % (name, ip))
self.child.timeout = 15
self.child.expect('password:')
self.child.sendline(pwd)
self.child.expect('#')
self.child.sendline('disable clipaging')
self.child.expect('#')
self.switch = Switch(name, ip, pwd, en_pwd, self.connected_interface)
print("Connected!")
return True
except (pexpect.EOF, pexpect.TIMEOUT):
attempts += 1
if "password" in str(self.child.before):
print("Wrong Credentials..")
return False
if "Host key verification failed." in str(self.child.before):
print("Host key verification failed. Retring!")
os.system('ssh-keygen -f "/root/.ssh/known_hosts" -R %s' % ip)
return self.connect_with_no_host_auth(ip, name, pwd)
if "The authenticity of host" in str(self.child.before):
return self.connect_with_no_host_auth(ip, name, pwd)
if attempts < max_attempts:
print("Attempt #%s failed! i'm triyng again!" % attempts)
else:
print("\n\n>>>>>>>>>>>CONNECTION ERROR<<<<<<<<<<<\n\n")
return False
def connect_with_no_host_auth(self, ip, name, pwd):
print("I'm trying to acknowledge the authenticity of the new host")
try:
self.child = pexpect.spawn("ssh %s@%s" % (name, ip))
self.child.expect('The authenticity of host')
self.child.sendline('yes')
self.child.expect('password:')
self.child.sendline(pwd)
self.child.expect('#')
self.child.sendline('disable clipaging')
self.child.expect('#')
print("Connected!")
self.switch = Switch(name, ip, pwd, pwd, self.connected_interface)
return True
except (pexpect.EOF, pexpect.TIMEOUT):
print("\n\n>>>>>>>>>>>CONNECTION ERROR<<<<<<<<<<<\n\n")
self.child.close()
return False
def take_interfaces(self):
self.child.sendline('show ports vid')
self.child.expect('#')
output = str(self.child.before)
raw_ports = re.findall('((\d+)\s+(Unt|T)*agged\s+(\d+([,]\s\d+)*|None)'
'(....\s+(Unt|T)*agged\s+(\d+([,]\s\d+)*|None))*)', output)
for raw_port in raw_ports:
if raw_port[1] != '':
p_number = raw_port[1]
vlans = list()
if raw_port[3] != 'None':
if ',' in raw_port[3]:
for vlan in raw_port[3].split(', '):
vlans.append(vlan)
else:
vlans.append(raw_port[3])
if raw_port[7] != 'None' and raw_port[7] != '':
if ',' in raw_port[7]:
for vlan in raw_port[7].split(', '):
vlans.append(vlan)
else:
vlans.append(raw_port[7])
mac_parts = self.switch_mac.split(':')
raw_mac = ''
for part in mac_parts:
raw_mac += part
num_mac = hex(int(raw_mac, 16) + int(p_number))[2:].zfill(12)
mac = ''
for index in range(0, len(num_mac)):
if index > 0 and (index % 2) == 0:
mac += ':'
mac += num_mac[index]
port = Port(p_number, mac)
if p_number not in self.switch_interfaces:
self.switch_interfaces.append(p_number)
self.switch.add_ports(port)
for vlan in vlans:
self.switch.set_blocked_port(mac, vlan, initialization=True)
return self.switch
def enable_monitor_mode(self):
try:
print("Enabling monitor mode...")
self.put_callback()
self.child.sendline('create mirror M1')
self.child.expect('#')
self.child.sendline('configure mirror M1 to port %s' % self.connected_interface)
self.child.expect('#')
for interface in self.switch_interfaces:
if interface != self.connected_interface:
self.child.sendline('configure mirror M1 add port %s' % interface)
self.child.expect('#')
self.child.sendline('enable mirror M1')
self.child.expect('(y/N)')
self.child.sendline('yes')
self.child.expect('#')
self.child.close()
except (pexpect.EOF, pexpect.TIMEOUT):
print("Connection Closed!")
def enable_monitor_mode_on_interface_range(self, interfaces):
try:
print("Enabling monitor mode...")
self.put_callback()
self.child.sendline('create mirror M1')
self.child.expect('#')
self.child.sendline('configure mirror M1 to port %s' % self.connected_interface)
self.child.expect('#')
for interface in interfaces:
if interface != self.connected_interface:
self.child.sendline('configure mirror M1 add port %s' % interface)
self.child.expect('#')
self.child.sendline('enable mirror M1')
self.child.expect('(y/N)')
self.child.sendline('yes')
self.child.expect('#')
self.child.close()
except (pexpect.EOF, pexpect.TIMEOUT):
print("Connection Closed!")
def enable_monitor_mode_on_specific_port(self, port_name):
try:
print("Enabling monitor mode...")
self.put_callback()
self.child.sendline('create mirror M1')
self.child.expect('#')
self.child.sendline('configure mirror M1 to port %s' % self.connected_interface)
self.child.expect('#')
self.child.sendline('configure mirror M1 add port %s' % port_name)
self.child.expect('#')
self.child.sendline('enable mirror M1')
self.child.expect('(y/N)')
self.child.sendline('yes')
self.child.expect('#')
self.child.close()
except (pexpect.EOF, pexpect.TIMEOUT):
print("Connection Closed!")
self.child.close()
def put_callback(self):
self.clear_upm_profile()
self.child.sendline('create upm profile disable_mirror')
self.child.expect('\n')
self.child.sendline('disable mirror M1')
self.child.expect('\r')
self.child.sendline('delete mirror M1')
self.child.expect('\r')
self.child.sendline('configure vlan %s add ports %s untagged' % (self.vlan, self.connected_interface))
self.child.expect('\r')
self.child.sendline('delete upm timer t')
self.child.expect('\r')
self.child.sendline('.')
self.child.expect('#')
self.child.sendline('create upm timer t')
self.child.expect('#')
self.child.sendline('configure upm timer t after %s' % self.monitor_timeout)
self.child.expect('#')
self.child.sendline('configure upm timer t profile disable_mirror')
self.child.expect('#')
self.child.sendline('enable upm timer t')
self.child.expect('#')
print("Finished!")
def clear_upm_profile(self):
print("Clearing UPM Profile")
self.child.sendline('delete upm profile disable_mirror')
self.child.expect('#')
print("Done")