-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMerakiAPIToolBox.py
More file actions
2717 lines (2489 loc) · 120 KB
/
MerakiAPIToolBox.py
File metadata and controls
2717 lines (2489 loc) · 120 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import meraki as mer
import csv
from tabulate import tabulate
import os
import json
import time
from mac_vendor_lookup import MacLookup as maclookup
from termcolor import colored, cprint
from concurrent import futures
from netaddr import *
import netaddr
import re
import socket
import readline
'''
Deprecated Imports
from ratelimit import limits, RateLimitException
from backoff import on_exception, expo
import random
import math
'''
''''''''''''''''''''''''
### GLOBALS ###
''''''''''''''''''''''''
# Verbosity
VERBOSE = False
# Indentation
INDENT = 0
# Logs go into a log directory and are $(unix time).log
LOGDIR = os.path.join(os.getcwd(), "logs")
LOGFILEPATH = os.path.join(LOGDIR, str(int(time.time())) + ".log")
# Meraki api calls generate a lot of cruff so we will jam them into here
MERLOGDIR = os.path.join(os.getcwd(), "meraki_logs")
if not os.path.isdir(LOGDIR):
os.mkdir(LOGDIR)
LOGFILE = open(LOGFILEPATH, "w")
else:
LOGFILE = open(LOGFILEPATH, "w")
if not os.path.isdir(MERLOGDIR):
os.mkdir(MERLOGDIR)
'''''''''''''''''''''''''''
### UTILITY FUNCTIONS ###
'''''''''''''''''''''''''''
# Controls verbose output
def printv(m):
if type(m) is list:
m = "[" + ', '.join(str(x) for x in m) + "]"
if VERBOSE:
printi("VERBOSE: " + str(m))
LOGFILE.write("VERBOSE: " + str(m) + "\n")
else:
LOGFILE.write("VERBOSE: " + str(m) + "\n")
# Indents output for us
def printi(m):
for line in m.split("\n"):
print("%s%s" % ("\t" * INDENT, line))
# Allows us to dump any dict into a csv format file
def dictToCSV(dic, filename):
keys = dic[0].keys()
with open(filename, 'w', encoding='utf8', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, fieldnames=dic[0].keys())
dict_writer.writeheader()
dict_writer.writerows(dic)
# Removes a key from a dictionary
def removeKey(d, key):
r = dict(d)
del r[key]
return r
# Formats a given dict that we can then use to send to the API
def formatDict(d, port):
# I gave up trying to make the null/None values work so if they are null/None they get burned to the ground
e = dict(d)
for k, v in d.items():
# There is a lot of information that the API returns to us that we do not need
if (v is None) or \
(v == '') or \
(v == []) or \
(port is True and 'number' in k) or \
(port is False and 'serial' in k):
del e[k]
return e
# If we are passed a list of macs we can sanitize our inputs using this
def formatMACS(macaddrs, filename):
if filename:
path = os.path.join(os.getcwd(), filename)
with open(path) as f:
macaddrs = f.readlines()
indexes = [2, 5, 8, 11, 14]
newmacaddrs = []
for macaddr in macaddrs:
# Remove whitespace, make it all lowercase, and remove any - or :
mac = str(macaddr).strip().upper().replace('-', '').replace(':', '')
for x in indexes:
if len(mac) <= x:
break
mac = mac[:x] + ":" + mac[x:]
newmacaddrs.append(mac)
return newmacaddrs
# For when we need just a single device.
def getDevice(dashboard, networks, name):
return [device for network in networks for device in dashboard.devices.getNetworkDevices(networkId=network['id'])
if device['name'].lower() == name.lower()]
# Organization => Networks => Devices => Clients
# This will return to us a list of networks
# If a filter exists, it will remove any networks in the filter
def getNetworks(dashboard, filterOut):
networks = []
for network in dashboard.networks.getOrganizationNetworks(organizationId=orgID):
'''
not any(x in network['name'] for x in filterOut)
not => negates the statement
any() => checks if there are any true values
x in network['name'] => iterates through all values of network['name'] and assigns their values to x
x in filterOut => for each value of x check if it is in filterOut
'''
if filterOut is None:
networks.append(network)
continue
if not any(x.lower() in network['name'].lower() for filters in filterOut for x in filters):
printv("Adding the network %s" % network['name'])
networks.append(network)
return networks
# Returns a list of all devices across all networks
# If any of the filters are in a device's LAN IP, Serial, Name, Tags, or Model, then it is added to our device list
def getDevices(dashboard, networks, deviceFilter, devices=None, filterOut=True, filterIn=False):
if deviceFilter is not None and len(deviceFilter) >= 1:
if type(deviceFilter[0]) is not list:
printv("Applying the filter of \"%s\"" % ','.join(deviceFilter))
else:
deviceFilter = [f for filt in deviceFilter for f in filt]
printv("Applying the filter from list of \"%s\"" % ','.join(deviceFilter))
else:
printv("There was no device filter")
if devices is None:
devices = []
printv("Creating a list of devices from our networks")
for network in networks:
for device in dashboard.devices.getNetworkDevices(networkId=network['id']):
if 'name' not in device:
device['name'] = device['mac']
devices.append(device)
printv("New devices length %d" % len(devices))
devFilter = []
newDevices = []
if deviceFilter is not None and len(deviceFilter) >= 1:
printv("Formatting the filters")
for filter in deviceFilter:
if is_ip(filter):
if '/' not in filter:
devFilter.append(IPNetwork(filter + '/32'))
else:
devFilter.append(filter.lower())
for device in devices:
if deviceFilter is None:
printv("Adding the device %s" % device['name'])
newDevices.append(device)
continue
else:
filtered = False
for filter in devFilter:
if filter in str(device['name']).lower() or \
filter in str(device['model']).lower() or \
filter in str(device['serial']).lower() or \
(type(filter) is IPNetwork and IPAddress(device['lanIp']) in filter):
# We can not expect all switches to be tagged so we do a special check for it
if 'tag' in device:
if any(tag for tag in device['tags'].strip().split(' ') if tag in [str(f) for f in filter]):
filtered = True
break
else:
printv("%s does not have any tags so we could not check the filter against it"
% device['name'])
filtered = True
break
# One of the devices values matches a passed in filter so now we check if we filter in or out
# Filtering the device out is our default
if not filtered and filterOut:
printv("Adding the device %s" % device['name'])
newDevices.append(device)
if filtered and filterIn:
printv("Adding the device %s" % device['name'])
newDevices.append(device)
return newDevices
else:
printv("Returning devices")
return devices
# Will tell us which network a switch belongs to
def getDeviceNetwork(serial, networks):
for network in networks:
for switch in dashboard.devices.getNetworkDevices(networkId=network['id']):
if switch['serial'] == serial:
return network
# Checks if device exists and returns true and the device if found or false and none otherwise
def is_device(devices, filter):
printv("Looking for a device with the filter of %s" % filter)
for device in devices:
if 'serial' in device and device['serial'].lower() == filter.lower() or \
'lanIp' in device and device['lanIp'] == filter or \
'name' in device and device['name'].lower() == filter.lower():
return device, True
return None, False
# Used when checking if vlans is all or when port number is not an int but something like g1
def is_int(x):
try:
num = int(x)
except ValueError:
return False
return True
# Used to determine if a given port exists on a switch
def is_port(dashboard, device, filter):
printv("Look for port %s on %s" % (filter, device['name']))
for port in dashboard.switch_ports.getDeviceSwitchPorts(device['serial']):
if str(port['number']) == str(filter):
return port, True
return None, False
def is_ip(i):
try:
if '/' not in i:
i += '/32'
j = IPNetwork(i)
else:
j = IPNetwork(i)
return True
except netaddr.core.AddrFormatError or ValueError:
return False
# In our main function almost all of its sub-functions will need the networks and devices variable correctly set
def checkVariables(devices, networks, networkFilter, deviceFilter):
if not networks:
printi("Getting networks")
networks = getNetworks(dashboard=dashboard, filterOut=networkFilter)
networks.sort(key=lambda x: x['name'])
if not devices:
printi("Finding devices in networks")
devices = getDevices(dashboard=dashboard, networks=networks, deviceFilter=deviceFilter)
devices.sort(key=lambda x: x['name'])
return networks, devices
# Breaks our very long device list up into X columns making it easier to read
def printDevices(devices, columns, detailed=False):
# If we are printing just a single switch
if type(devices) is not list:
filter = ['name', 'url', 'model', 'mac', 'tags', 'serial', 'networkId']
temp = dict()
for key in filter:
if key not in devices:
temp[key] = 'None'
for k, v in devices.items():
if k in filter:
temp[k] = v
printi(json.dumps(temp, indent=4))
elif detailed:
data = []
for device in devices:
data.append([device['name'], device['serial'], device['model'],
device['lanIp'], device['mac'], device['url']])
data.sort(key=lambda x: x[0])
data.insert(0, ["Name", "Serial", 'Model', 'IP', 'MAC', 'URL'])
printi(tabulate(data, headers='firstrow'))
else:
printi(tabulate(divideChunks([device['name'] for device in devices], columns)))
# Allows us to split a list up into chunks
def divideChunks(lst, chunks):
# looping till length l
for i in range(0, len(lst), chunks):
yield lst[i:i + chunks]
# Confirms we have a dashboard instance
def getDashboard(apikey, maxRetry):
try:
dashboard = mer.DashboardAPI(api_key=apikey,
print_console=False,
maximum_retries=maxRetry,
wait_on_rate_limit=True,
log_path=MERLOGDIR)
return dashboard, True
except:
return None, None
# returns a properly formatted mac address
def formatMACAddr(mac):
indexes = [2, 5, 8, 11, 14]
# Remove whitespace, make it all lowercase, and remove any - or :
macaddr = str(mac).strip().upper().replace('-', '').replace(':', '')
for x in indexes:
if len(mac) <= x:
break
macaddr = macaddr[:x] + ":" + macaddr[x:]
printv(macaddr)
return macaddr
# Utility function that pairs with the gatherMacs primary function to locate a mac address on our network
def findMacs(macDict, macs, vendors):
data = []
if bool(vendors):
for ven in macDict.keys():
# sorry not sorry
if any(vend for vend in vendors if ven.lower() in vend.lower()):
printv("if statement resulted in true for the vednor \"%s\"" % ven)
for macaddr in macDict[ven]:
for deviceName, port in macDict[ven][macaddr]:
data.append([ven, macaddr, deviceName, port])
if bool(macs):
for ven in macDict.keys():
for macaddr in macDict[ven]:
if any(mac for mac in macs if formatMACAddr(macaddr) in formatMACAddr(mac)):
printv("if statement resulted in true for the mac \"%s\"" % formatMACAddr(macaddr))
for deviceName, port in macDict[ven][macaddr]:
data.append([ven, macaddr, deviceName, port])
data.insert(0, ['Vendor', 'MacAddr', 'Device', 'Port'])
printi(tabulate(data, headers='firstrow'))
# Helper function to print mac data
def printMacs(macDict):
data = []
for vendor in macDict.keys():
for mac in macDict[vendor]:
for location in macDict[vendor][mac]:
data.append([
vendor,
mac,
location[0],
location[1]
])
data.insert(0, ['Vendor', 'MacAddr', 'Device', 'Port'])
printi(tabulate(data, headers='firstrow'))
# Helper function used for printing out switch port information
def printSwitchPorts(switchPorts):
data = []
for k in switchPorts.keys():
for ports in switchPorts[k]:
data.append([k] + [p for p in ports.values()])
data.insert(0, ['Switch', 'Number', 'Name', 'Tags', 'Enabled', 'POE Enabled', 'Type', 'VLAN',
'Voice VLAN', 'Allowed VLANs', 'RSTP Enabled', 'STP Guard'])
printi(tabulate(data, headers='firstrow'))
def getNetwork(networks):
printi("Please select a network to work with")
for x, network in enumerate(networks):
printi("%d: %s" % (x + 1, network['name']))
network = input(prompt)
networkId = None
while not is_int(network) and (1 < int(network) > len(networks)):
printi("Invalid choice. Please choose a number from 1 to %d or 0 to go back" % len(networks))
network = input(prompt)
if network == '0':
return None
if network == '0':
return None
else:
return networks[int(network) - 1]
'''
### PRIMARY FUNCTIONS
'''
# Original logic written by Nico Darrow of Meraki
# Translated and adjusted for this API Tool by Adam Littrell
# Switches need to be unstacked before migrating
# Port aggregation isn't supported (aggregated ports will be split)
# L3 Interfaces / DHCP scopes / ACLs will not be migrated
def migrateSwitches(dashboard, srcNetwork, dstNetwork, tag, whatIf):
srcNetId = srcNetwork['id']
dstNetId = dstNetwork['id']
if whatIf:
printv("We are doing a switch migration test run")
printv("We will be migrating the switches from %s with the tag of %s to %s" % (
srcNetwork['name'], tag, dstNetwork['name']
))
else:
printv("We are doing a live switch migration")
printv("We will be migrating the switches from %s with the tag of %s to %s" % (
srcNetwork['name'], tag, dstNetwork['name']
))
inScopeDevices = []
for device in dashboard.devices.getNetworkDevices(srcNetId):
if 'tag' in device and tag in device['tag']:
inScopeDevices.append(device)
if whatIf:
printi("The following devices would be moved")
printDevices(inScopeDevices, 5)
return
# Migrating the switches
for device in inScopeDevices:
# Making our backups
printv("Making our backup for %s" % device['name'])
filename = str(int(time.time())) + "_" + device['name'] + "_backup.json"
ports = dashboard.switch_ports.getDeviceSwitchPorts(device['serial'])
device['ports'] = ports
with open(filename, 'w') as f:
printv("Saving %s configuration to file" % device['name'])
json.dump(device, f)
# Unclaiming the devices for source network and claiming them in destination network
printv("Migrating %s to new network" % device['name'])
dashboard.devices.removeNetworkDevice(srcNetId, serial=device['serial'])
dashboard.devices.claimNetworkDevices(dstNetId, serial=device['serial'])
# Restoring port configuration on the switch
for port in ports:
p = formatDict(port, port=True)
dashboard.switch_ports.updateDeviceSwitchPort(serial=device['serial'], number=port['number'], **p)
printi("Migration complete")
# Transfers the port configuration from point A to point B
def copySwitchPortConfig(dashboard, sSwitch, sPort, dSwitch, dPort):
# First we get the source switch port config
sourcePort = dashboard.switch_ports.getDeviceSwitchPort(sSwitch['serial'], number=sPort['number'])
printv("Original source port configuration (null = None)")
printv(json.dumps(sourcePort, indent=4))
printv("Original destination port configuration (null = None)")
destPort = dashboard.switch_ports.getDeviceSwitchPort(dSwitch['serial'], number=dPort['number'])
printv(json.dumps(destPort, indent=4))
# Then we remove the number key from the dict
kwargsDict = formatDict(sourcePort, port=True)
printv("Formatted configuration")
printv(json.dumps(kwargsDict, indent=4))
# Lastly we pass our dict, ie our source port config, over to the destination port configuration
dashboard.switch_ports.updateDeviceSwitchPort(serial=dSwitch['serial'], number=dPort['number'], **kwargsDict)
destPort = dashboard.switch_ports.getDeviceSwitchPort(dSwitch['serial'], number=dPort['number'])
printv("New destination port configuration")
printv(json.dumps(destPort, indent=4))
# This needs to be re-written and has been pulled out of rotation until it can be re-written
# Needs to have standardized inputs, less try catch, and vlan formatting moved to utility function
# getSwitchVLANS function contains the log we will need
def findPortsByVLAN(dashboard, vlan, networks):
data = []
data.append(['Switch', 'Port', 'Network', 'URL'])
for network in networks:
if "DC" in network['name'] and "wireless" not in network['name']:
tmp = dashboard.devices.getNetworkDevices(networkId=network['id'])
devices = sorted(tmp, key=lambda k: k['name'])
for device in devices:
try:
for port in dashboard.switch_ports.getDeviceSwitchPorts(device['serial']):
vlanList = []
for vlan in str(port['allowedVlans']).split(','):
if "-" in vlan:
for i in range(int(vlan.split("-")[0]), int(vlan.split("-")[1])):
if int(i) not in vlanList:
vlanList.append(int(i))
vlanList.sort()
else:
if ("all" not in vlan) and (int(vlan) not in vlanList):
vlanList.append(int(vlan))
vlanList.sort()
if vlan in vlanList:
data.append([device['name'],
str(port['number']),
network['name'],
device['url']
])
printv("Finished with the \"%s\" switch" % device['name'])
except:
printv("We ran into an error with the \"%s\" switch" % device['name'])
printi(tabulate(data, headers='firstrow'))
# Will return a list of all vlans on all switches
def getSwitchVLANS(devices):
vlans = dict()
data = []
for device in devices:
# We use a set since we dont want duplicates and itll make our code easier to read
vlans[device['name']] = set()
for port in dashboard.switch_ports.getDeviceSwitchPorts(device['serial']):
# port['vlan']
if 'vlan' in port and is_int(port['vlan']):
vlans[device['name']].add(int(port['vlan']))
# port['allowedVlans']
for vlan in str(port['allowedVlans']).split(','):
# 'allowedVlans': '20-21,78,81,1prompt,128,130,150,270,296,328'
if "-" in vlan:
for i in range(int(vlan.split("-")[0]), int(vlan.split("-")[1])):
vlans[device['name']].add(i)
elif "all" not in str(vlan):
vlans[device['name']].add(int(vlan))
vlans[device['name']] = sorted(vlans[device['name']])
# We are returning the dict and will handle the printing elsewhere
return vlans
# If a port is connected then it is considered in use. Takes number of in use and divides it by total
# Take this information with a grain of salt because there is a lot of assumptions I skip out of laziness
# Need to add a feature that will print out which switches have 1-10,10-20,20-30,30-35,35-40,40-48 ports connected
def getPortUsageStats(dashboard, devices):
inUsePorts = 0
totalPorts = 0
waste_check = []
for device in devices:
deviceInUse = 0
deviceTotal = 0
for port in dashboard.switch_ports.getDeviceSwitchPortStatuses(serial=device['serial']):
if port['status'] == "Connected":
inUsePorts += 1
totalPorts += 1
deviceInUse += 1
deviceTotal += 1
else:
totalPorts += 1
deviceTotal += 1
printv(device['name'] + " is at " + "{:.2%}".format(deviceInUse / deviceTotal) + " allocation")
percent = deviceInUse / deviceTotal
if percent <= 1.1:
waste_check.append([device['name'],
deviceInUse,
deviceTotal,
"{:.2%}".format(percent)])
waste_check.sort(key=(lambda x: x[1] / x[2]))
waste_check.insert(0, ["Name", "In Use", "Total", "Allocation"])
printi("Total Switches: %s" % len(devices))
printi("Total Ports: %s" % totalPorts)
printi("In Use Ports: %s" % inUsePorts)
printi("Port allocation: " + "{:.2%}".format(inUsePorts / totalPorts))
printi("Switches worth investigating:")
printi(tabulate(waste_check, headers='firstrow'))
# This will gather all the MAC address seen by all the given switches
# We can then pass this information over to a lookup function and thus have an easy way to locate macs
# The use of multithreading is crucial here for without it, this will take over 4 minutes to complete
def gatherMacs(dashboard, devices, networks):
'''
Notes:
I could never get this to work properly. Despite setting it to be 5 calls per second as per Meraki rules,
I was still getting 429 rate limit errors. I messed around with this a lot, and even told the Dashboard API
library to wait and try again after the 429 errors but with no luck. I decided to put making the processing
part of the function multithreaded. It goes by about as fast if I double the thread limit
# The api only allows us 5 calls per second
# By having this limiter and exponential back-off, we can maximize speed without worry
@on_exception(expo, RateLimitException, max_tries=10)
@limits(calls=5, period=1)
def callAPI(device, networkId, clients, lldp):
error = 1
while True:
try:
if clients:
ret = dashboard.clients.getDeviceClients(serial=device['serial'], timespan=1296000)
if lldp:
ret = dashboard.devices.getNetworkDeviceLldp_cdp(networkId=networkId,
serial=device['serial'],
timespan=1296000)
print("%s LEAVING API CALL" % device['name'])
return ret
except:
print("%s GOT ERROR FOR %d TIME" % (device['name'], error))
error += 1
time.sleep(random.uniform(3, 5))
'''
# The first place to look for a MAC is LLDP/CDP
def processDeviceLLDP(device, ports, networkId):
printv("%s is in LLDP" % device['name'])
# Getting our master dicts created
masterDic = dict()
masterDic['Unknown'] = dict()
printv("Working with %s" % device['name'])
printv("Checking LLDP/CDP information")
# Using our rate limit function to call our api and get our LLDP information
# ports = callAPI(device=device, networkId=networkId, lldp=True, clients=False)
if 'ports' in ports and bool(ports):
# Iterating through all the ports and gathering their information
for port in ports['ports']:
# LLDP
if 'lldp' in ports['ports'][port]:
# Getting MAC
if 'portId' in ports['ports'][port]['lldp'] and bool(ports['ports'][port]['lldp']['portId']):
portIDCheck = ports['ports'][port]['lldp']['portId']
if len(str(portIDCheck).replace(':', '')) == 12:
portid = formatMACAddr(portIDCheck)
# Seeing if we can get a vendor
try:
vendor = maclookup().lookup(portid)
# Checking if we have a vendor dict
if vendor not in masterDic:
masterDic[vendor] = dict()
# Checking if we have a MAC array in the vendor
if portid not in masterDic[vendor]:
masterDic[vendor][portid] = []
# Checking if we already have the switch,port tuple in the array
if (device['name'], port) not in masterDic[vendor][portid]:
masterDic[vendor][portid].append((device['name'], port))
else:
printv("(%s,%s) already exists for the mac %s for the vendor %s" %
(device['name'], port, portid, vendor))
except:
printv("On switch %s port %s we could not get a vendor for the mac %s" %
(device['name'], port, portid))
if portid not in masterDic['Unknown']:
masterDic['Unknown'][portid] = []
if (device['name'], port) not in masterDic['Unknown'][portid]:
masterDic['Unknown'][portid].append((device['name'], port))
else:
printv("(%s,%s) already exists for the mac %s in the unknowns" %
(device['name'], port, portid))
# CDP
if 'cdp' in ports['ports'][port]:
# Getting MAC
if 'deviceId' in ports['ports'][port]['cdp']:
deviceIDCheck = ports['ports'][port]['cdp']['deviceId']
if len(str(deviceIDCheck).replace(':', '')) == 12:
deviceId = formatMACAddr(deviceIDCheck)
# Seeing if we can get a vendor
try:
vendor = maclookup().lookup(deviceId)
# Checking if we have a vendor dict
if vendor not in masterDic:
masterDic[vendor] = dict()
# Checking if we have a MAC array in the vendor
if deviceId not in masterDic[vendor]:
masterDic[vendor][deviceId] = []
# Checking if we already have the switch,port tuple in the array
if (device['name'], port) not in masterDic[vendor][deviceId]:
masterDic[vendor][deviceId].append((device['name'], port))
else:
printv("(%s,%s) already exists for the mac %s for the vendor %s" %
(device['name'], port, deviceId, vendor))
except:
printv("On switch %s port %s we could not get a vendor for the mac %s" %
(device['name'], port, deviceId))
if deviceId not in masterDic['Unknown']:
masterDic['Unknown'][deviceId] = []
if (device['name'], port) not in masterDic['Unknown'][deviceId]:
masterDic['Unknown'][deviceId].append((device['name'], port))
else:
printv("(%s,%s) already exists for the mac %s in the unknowns" %
(device['name'], port, deviceId))
else:
printv("Skipping %s since there are no ports" % device['name'])
return masterDic
# The next place to look for a MAC is in the clients table
def processDeviceClients(device, clients):
# Getting our master dicts created
masterDic = dict()
masterDic['Unknown'] = dict()
printv("Working with %s" % device['name'])
printv("Checking clients on %s" % device['name'])
# Now we check the clients on the switch using our rate limit function
# clients = callAPI(device=device, clients=True, networkId=None, lldp=False)
# Now we iterate through all the clients
printv("Checking all %s clients on switch %s" % (len(clients), device['name']))
for client in clients:
'''
'id': 'k6cfdd8',
'mac': '54:27:58:d0:27:8e',
'description': 'android-7e3242c6007b60f6',
'mdnsName': None, 'dhcpHostname':
'android-7e3242c6007b60f6',
'ip': '10.170.9.62',
'vlan': 270,
'switchport': '5',
'usage': {'sent': 56.0, 'recv': 213.0}}
'''
if 'mac' in client and bool(client['mac']):
mac = formatMACAddr(client['mac'])
# Seeing if we can get a vendor
try:
vendor = maclookup().lookup(mac)
# Checking if we have a vendor dict
if vendor not in masterDic:
masterDic[vendor] = dict()
# Checking if we have a MAC array in the vendor
if mac not in masterDic[vendor]:
masterDic[vendor][mac] = []
# Checking if we already have the switch,port tuple in the array
if (device['name'], client['switchport']) not in masterDic[vendor][mac]:
masterDic[vendor][mac].append((device['name'], client['switchport']))
else:
printv("(%s,%s) already exists for the mac %s for the vendor %s" %
(device['name'], client['switchport'], mac, vendor))
except:
printv("On switch %s port %s we could not get a vendor for the mac %s" %
(device['name'], client['switchport'], mac))
if mac not in masterDic['Unknown']:
masterDic['Unknown'][mac] = []
if (device['name'], client['switchport']) not in masterDic['Unknown'][mac]:
masterDic['Unknown'][mac].append((device['name'], client['switchport']))
else:
printv("(%s,%s) already exists for the mac %s in the unknowns" %
(device['name'], client['switchport'], mac))
return masterDic
# Now we go through and call the above inner functions
start = str(int(time.time()))
printv("Starting the thread pool at %s" % start)
printi("Making API calls to gather required information")
# We can have this many workers because our rate limit inner function will prevent us from hitting the max
with futures.ThreadPoolExecutor(max_workers=100) as executor:
devicePool = []
for device in devices:
# We put these sleep statements in to help reduce the number of back-offs needed
printv("sending the device %s into the thread pool" % device['name'])
# Getting our network id
start = time.time()
if 'networkId' in device:
networkId = device['networkId']
else:
network = getDeviceNetwork(device['serial'], networks)
networkId = network['id']
finish = time.time()
networkTime = finish - start
printv("%s -> Get Network -> %f" % (device['name'], networkTime))
start = time.time()
ports = dashboard.devices.getNetworkDeviceLldp_cdp(networkId=networkId,
serial=device['serial'],
timespan=1296000)
finish = time.time()
networkTime = finish - start
printv("%s -> Get Ports -> %f" % (device['name'], networkTime))
devicePool.append(executor.submit(processDeviceLLDP, device, ports, networkId))
start = time.time()
clients = dashboard.clients.getDeviceClients(serial=device['serial'], timespan=1296000)
finish = time.time()
networkTime = finish - start
printv("%s -> Get Ports -> %f" % (device['name'], networkTime))
devicePool.append(executor.submit(processDeviceClients, device, clients))
printv("Now we are waiting for the threads to complete")
printi("Finished making API calls")
printi("Processing returned data")
complete_futures, incomplete_futures = futures.wait(devicePool)
finish = str(int(time.time()))
printv("All jobs have finished at %s" % finish)
printv("Time to complete %s" % str(int(start) - int(finish)))
printv("Now getting all the results from the complete pool")
# The time that we save using multithreading makes this mess totally worth it
completeMasterDic = dict()
for complete in complete_futures:
for key in complete.result().keys():
# If the Vendor is not already in the master dict then we add it in and then go through the macs
if key not in completeMasterDic:
completeMasterDic[key] = dict()
# Now we go through the macs in the vendor
for macs in complete.result()[key]:
# If the vendor does not have this mac address then we add it in
if macs not in completeMasterDic[key]:
completeMasterDic[key][macs] = []
# Now we go through the mac and add any non duplicate tuples
for deviceTuple in complete.result()[key][macs]:
# If the tuple is not in the array then we add it in
if deviceTuple not in completeMasterDic[key][macs]:
completeMasterDic[key][macs].append(deviceTuple)
else:
printv("%s was a duplicate tuple for %s->%s" % (str(deviceTuple), key, macs))
# In theory this should never run but I am leaving it here just in case
if len(incomplete_futures) > 0:
printv("Something did not get a chance to complete and that is bad")
printv("Not sure what you can do about that though so I guess you can ignore this error?")
for incomplete in incomplete_futures:
printv(incomplete.result())
# For testing purposes, we will print the newly made dict and then return it
printv(json.dumps(completeMasterDic, indent=4))
return completeMasterDic
# Will list out any LLDP/CDP information for any amount of switches
# It will also try to map any MACs to Vendors for extra information
def getLLDPCDPInfo(dashboard, devices, networks):
'''
See notes on the gatherMACS function as to why this was removed
# The api only allows us 5 calls per second
# By having this limiter and exponential back-off, we can maximize speed without worry
@on_exception(expo, RateLimitException, max_tries=10)
@limits(calls=5, period=3)
def callAPI(device, networkId):
print("%s is making a thread call" % device['name'])
return dashboard.devices.getNetworkDeviceLldp_cdp(networkId=networkId,
serial=device['serial'],
timespan=1296000)
'''
def getInfo(device, ports):
data = []
printv("working with %s" % device['name'])
# If we ports is an empty dict then we just move on to the next device
if not bool(ports):
return []
for port in ports['ports']:
# LLDP
if 'lldp' in ports['ports'][port]:
# Getting the system name
if 'systemName' in ports['ports'][port]['lldp']:
deviceName = ports['ports'][port]['lldp']['systemName']
if "MR42" not in deviceName:
# Removes the first bit and only gives us the switch name
# ex Meraki MS425-32 - WDCB125SW01 => WDCB125SW01
if 'Meraki' in str(ports['ports'][port]['lldp']['systemName']).split(" - ", 1)[0]:
deviceName = str(ports['ports'][port]['lldp']['systemName']).split(" - ", 1)[1]
else:
deviceName = str(ports['ports'][port]['lldp']['systemName']).split(" - ", 1)[0]
else:
printv("Wireless Device \"%s\" skipped" % deviceName)
continue
elif 'portId' in ports['ports'][port]['lldp'] and bool(ports['ports'][port]['lldp']['portId']):
portID = str(ports['ports'][port]['lldp']['portId']).replace(':', '')
if len(portID) == 12:
try:
deviceName = maclookup().lookup(ports['ports'][port]['lldp']['portId'])
except:
deviceName = "N/A"
else:
deviceName = "N/A"
else:
deviceName = "N/A"
# Getting MAC
if 'portId' in ports['ports'][port]['lldp'] and bool(ports['ports'][port]['lldp']['portId']):
destport = ports['ports'][port]['lldp']['portId']
if len(str(destport).replace(':', '')) == 12:
try:
vendor = maclookup().lookup(destport)
destport = "%s (%s)" % (destport, vendor)
except:
printv("Couldnt get a vendor for the mac %s" % destport)
else:
destport = "N/A"
# Getting IP
if 'managementAddress' in ports['ports'][port]['lldp'] and \
bool(ports['ports'][port]['lldp']['managementAddress']):
destip = ports['ports'][port]['lldp']['managementAddress']
else:
destip = "N/A"
# CDP
elif 'cdp' in ports['ports'][port]:
if 'deviceId' in ports['ports'][port]['cdp']:
portID = str(ports['ports'][port]['cdp']['portId']).replace(':', '')
if len(portID) == 12:
try:
deviceName = maclookup().lookup(ports['ports'][port]['cdp']['portId'])
except:
deviceName = "N/A"
else:
deviceName = "N/A"
else:
deviceName = "N/A"
if 'address' in ports['ports'][port]['cdp'] and bool(ports['ports'][port]['cdp']['address']):
destip = ports['ports'][port]['cdp']['address']
if not bool(destip):
destip = "N/A"
else:
destip = "N/A"
if 'portId' in ports['ports'][port]['cdp'] and bool(ports['ports'][port]['cdp']['portId']):
destport = ports['ports'][port]['cdp']['portId']
if len(str(destport).replace(':', '')) == 12:
try:
vendor = maclookup().lookup(destport)
destport = "%s (%s)" % (destport, vendor)
except:
printv("Couldnt get a vendor for the mac %s" % destport)
else:
destport = "N/A"
else:
continue
# Lastly we check if port can be an int to help with our sort
if is_int(port):
port = int(port)
data.append([device['name'],
port,
deviceName,
destport,
destip
])
return data
# Now we go through and call the above inner functions
start = str(int(time.time()))
printv("Starting the thread pool at %s" % start)
if type(devices) is not list:
printv("Single device sent in")
devices = [devices]
with futures.ThreadPoolExecutor(max_workers=50) as executor:
devicePool = []
for device in devices:
# We put these sleep statements in to help reduce the number of back-offs needed
printv("sending the device %s into the thread pool" % device['name'])
# Getting our network id
start = time.time()
if 'networkId' in device:
networkId = device['networkId']
else:
network = getDeviceNetwork(device['serial'], networks)
networkId = network['id']
finish = time.time()
networkTime = finish - start
printv("%s -> Get Network -> %f" % (device['name'], networkTime))
start = time.time()
ports = dashboard.devices.getNetworkDeviceLldp_cdp(networkId=networkId,
serial=device['serial'],
timespan=1296000)
finish = time.time()
networkTime = finish - start
printv("%s -> Get Ports -> %f" % (device['name'], networkTime))
devicePool.append(executor.submit(getInfo, device, ports))
printv("Now we are waiting for the threads to complete")
complete_futures, incomplete_futures = futures.wait(devicePool)
finish = str(int(time.time()))
printv("All jobs have finished at %s" % finish)
printv("Time to complete %s" % str(int(finish) - int(start)))
printv("Now getting all the results from the complete pool")
masterData = []
for complete in complete_futures:
for data in complete.result():
if data is not []:
masterData.append(data)
# Not going to lie here, I fell asleep during my CMSC330 Lambda lecture so I needed stack overflow
# https://stackoverflow.com/questions/6666748/python-sort-list-of-lists-ascending-and-then-decending
masterData.sort(key=lambda x: (x[0], x[1]))
masterData.insert(0, ["S-Switch", "S-Port", "D-Switch", "D-Port", "D-IP"])
printi(tabulate(masterData, headers='firstrow'))
printi("\n")
# WIP. Goal: Change the wifi password across all sites and update accordingly