/
functions.py
375 lines (296 loc) · 10.3 KB
/
functions.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
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
import paramiko as pm
import csv_output
import threading
import datetime
import pathlib
import netmiko as nm
import socket
import re
import csv_failures
global threads
global list
global telnetList
global netmikoList
global username
global password
global usernameAlt
global passwordAlt
global failures
global hostFailsCount
class AllowAllKeys(pm.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return
def CLIPrompt():
username=input("Enter Devices' Username:")
newline=input(":")
password=input("Enter Devices' Password:")
def setCredentials(user,passwd):
global username
global password
username=user
password=passwd
ipregex=re.compile(r"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])")
#actually extracts IPs from given text
def formatInput(hosts):
ipregex = re.compile(
#Valid IPs
r"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])")
tmp=hosts[:]
# Attempt to Format list
formatted1=[]
formatted=[]
for e in tmp:
try:
formatted1.append(re.search(ipregex,e).groups(1))
except Exception as exeption:
pass
for e in formatted1:
stringIP=""
i=0
for ee in e:
if i == 0 :
stringIP=ee
else:
stringIP+="."+ee
i+=1
formatted.append(stringIP)
#remove dublicates
tmp2=[]
for i in formatted:
if i not in tmp2:
tmp2.append(i)
return tmp2
#check if the input IPs are valid and remove invalid ones
#kind of useless after formating
def checkIPs(hosts):
illegalips = []
for e in hosts:
if re.match(ipregex, e):
pass
else:
hosts.remove(e)
illegalips.append(e)
continue
if e.isspace() or not e :
hosts.remove(e)
illegalips.append(e)
continue
if not re.match(ipregex, e):
print("regular",e)
hosts.remove(e)
illegalips.append(e)
continue
try:#if not valid ip it will throw exception
socket.inet_aton(e)
# legal
except socket.error:
hosts.remove(e)
illegalips.append(e)
continue
# Not legal
print("-List of hosts :")
for element in hosts:
print(element)
print("Illegal IPs :",illegalips)
if len(illegalips)==0:
return True
else :
return False
def parseCommands(filename):
with open('CiscoCommandsToExecute.txt', 'r') as content_file:
commands = content_file.read()
return commands
state=""
def telnetCommands(host,event,commands,type,user,passwd,retry):
global telnetList
global failures
state="OK"
output=[]
stre = "None"
lines = commands.splitlines()
#Using netmiko telnet client
net_connect = None
try:
device = {
'device_type': 'cisco_ios_telnet',
'ip': host,
'username': user,
'password': passwd,
'timeout': 40
}
net_connect = nm.ConnectHandler(**device)
lines = commands.splitlines()
for command in lines:
if type == 0:
output.append(net_connect.send_config_set(command) + "\n")
else:
output.append(net_connect.send_command_timing(delay_factor=1.5,command_string=command) + "\n")
try:
net_connect.disconnect()
except:
print("Disconnected ",host)
except Exception as e:
print("type error: " + str(e))
stre = str(e)
state = "Exception"
global hostFailsCount
if ("login" in str(e) ):
print("Trying with alternative user/pass")
failures.append([host, "Telnet-Auth"])
hostFailsCount[host] += 1
if retry != 2 and (usernameAlt!="" and passwordAlt!=""):
retry+=1
telnetCommands(host,event,commands,type,usernameAlt,passwordAlt,retry)
return
elif "period" in str(e):
print("Timed out")
failures.append([host, "Telnet-Timeout"])
if (usernameAlt == "" or passwordAlt == ""):
hostFailsCount[host] += 1
else:
hostFailsCount[host] += 2
else:
hostFailsCount[host] += retry
telnetList.append({"host": host, "state": state, "info": output, "details": stre, "Commands": lines})
return
telnetList.append({"host": host, "state": state, "info": output, "details": stre, "Commands": lines})
print("Output:", output)
def executeCommandsNetmiko(host,event,commands,type,user,passwd,retry):
global netmikoList
global failures
state="OK"
info="No output"
stre="None"
output=[]
lines = commands.splitlines()
net_connect = None
try:
device = {
'device_type': 'cisco_ios',
'ip': host,
'username': user,
'password': passwd,
'port': 22,
'global_delay_factor': 1,
'verbose': True,
'timeout' : 40
}
net_connect = nm.ConnectHandler(**device)
for command in lines :
if type == 0:
output.append(net_connect.send_config_set(command)+"\n")
else:
output.append(net_connect.send_command_timing(delay_factor=1.5,command_string=command)+"\n")
state="OK"
print(output)
try:
net_connect.disconnect()
except:
print("Disconnected ",host)
except Exception as e:
print("type error: " + str(e))
stre=str(e)
state = "Exception"
if ("Authenticat" in str(e) ):
print("Trying with alternative user/pass")
failures.append([host, "SSH-Auth"])
hostFailsCount[host] += 1
if retry != 2 and (usernameAlt!="" and passwordAlt!=""):
retry+=1
executeCommandsNetmiko(host,event,commands,type,usernameAlt,passwordAlt,retry)
return
elif "timed-out" in str(e):
print("Timeout SSH")
failures.append([host, "SSH-Timeout"])
if (usernameAlt == "" or passwordAlt == ""):
hostFailsCount[host] += 1
else:
hostFailsCount[host] += 2
else:
hostFailsCount[host] += retry
netmikoList.append({"host": host, "state": state, "info": output, "details": stre, "Commands": lines })
return
netmikoList.append({"host": host, "state": state, "info": output, "details": stre,"Commands":lines})
def mainLogic(hosts,commands,user,passwd,commandType,userAlt,passwdAlt) :
global list
global username
global password
username=user
password=passwd
global usernameAlt
global passwordAlt
usernameAlt=userAlt
passwordAlt=passwdAlt
threads=[]
list=[]
global failures
failures=[]
global hostFailsCount
hostFailsCount={}
for host in hosts:
hostFailsCount[host] = 0
#Stage 1
#Try with netmiko for each failed device after stage 1
now = datetime.datetime.now()
outputdir = 'Results-' + now.strftime("%Y-%m-%d %H_%M")
pathlib.Path(outputdir).mkdir(parents=True, exist_ok=True)
pathlib.Path(outputdir + "/SuccessTXT").mkdir(parents=True, exist_ok=True)
threads=[]
global netmikoList
netmikoList=[]
print("Trying devices with SSH Please wait... Devices: ", hosts)
for e in hosts:
event = threading.Event()
deviceThread = threading.Thread(target=executeCommandsNetmiko, args=(e, event,commands,commandType,username,password,1))
threads.append(deviceThread)
deviceThread.start()
#wait for all threads from stage 2 to finish
for thread in threads:
thread.join()
if netmikoList!=[]:
csv_output.output(netmikoList,"SSH Results - "+now.strftime("%Y-%m-%d %H_%M"),outputdir)
print("Check->",netmikoList)
threads=[]
global telnetList
telnetList=[]
#Start stage 3 : try with telnet connection (Netmiko)
print("Trying failed devices with Telnet Please wait... ")
for e in netmikoList:
if not "OK" in e["state"]:#e.get('state', " "):
print(str(e))
event = threading.Event()
deviceThread = threading.Thread(target=telnetCommands,args=(e["host"], event,commands,commandType,username,password,1))
threads.append(deviceThread)
deviceThread.start()
#wait for all failed telnet accessed devices to finish
# print("join")
for thread in threads:
thread.join()
if telnetList!=[]:
csv_output.output(telnetList, "TelnetResults - "+now.strftime("%Y-%m-%d %H_%M"), outputdir)
failures.sort(key=lambda x: x[0])
csv_failures.output(failures, "All failures - " + now.strftime("%Y-%m-%d %H_%M"), outputdir)
universallFails=[]
success=[]
for host in hosts:
for e in netmikoList:
if "OK" in e["state"]:
success.append(e["host"])
for e in telnetList:
if "OK" in e["state"]:
success.append(e["host"])
universallFails = []
allmethosFailsTotal=0
print(hostFailsCount)
for host in hosts:
if (hostFailsCount[host] >= 4 and (usernameAlt != "" and passwdAlt != "" ) ):
universallFails.append([host, "Failed After All the Steps", hostFailsCount[host]])
elif (hostFailsCount[host] >= 2 and (usernameAlt == "" or passwdAlt == "")):
universallFails.append([host, "Failed After All the Steps", hostFailsCount[host]])
print("Universally Failed" + str(len(hostFailsCount)))
if (len(universallFails) != 0 ):
csv_failures.output(universallFails, "Universally Failed - " + now.strftime("%Y-%m-%d %H_%M"), outputdir)
print("Universally Failed")
print("########################################################")
print("Finished executing cli commands on all devices")
print("Your results are in the " + outputdir + " folder")