-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsak
executable file
·2083 lines (1902 loc) · 102 KB
/
msak
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
#!/usr/bin/env python3
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import aiohttp
import asyncio
import json
import argparse
import os
import yaml
import logging
import re
import requests
import time
import pprint
import sys
import traceback
from dictdiffer import diff
import jsonschema
from jsonschema import validate
from aiohttp.client_exceptions import ClientError
import pandas as pd
import meraki
DEFAULT_MERAKI_BASE_URL = 'https://api.meraki.com/api/v1'
CONFIG_FILES = ['/etc/meraki/meraki_inventory.yml', '/etc/ansible/meraki_inventory.yml']
OPENAPI_SPEC_FILE = 'meraki-openapi-spec.json'
API_MAX_RETRIES = 3
API_CONNECT_TIMEOUT = 60
API_TRANSMIT_TIMEOUT = 60
API_STATUS_RATE_LIMIT = 429
API_RETRY_DEFAULT_WAIT = 3
PRODUCT_TYPES = [
'appliance',
'switch',
'wireless',
'sensor',
'camera',
'cellularGateway'
]
PRODUCT_TYPES_MAP = {
'appliance': ['MX'],
'wireless': ['MR', 'CW'],
'switch': ['MX']
}
readonly_exceptions = [
"/organizations/{organizationId}/inventory/devices"
]
index_lookup = {
"/networks/{networkId}/switch/accessPolicies": "accessPolicyNumber",
"/networks/{networkId}/wireless/ssids": "number",
"/networks/{networkId}/groupPolicies": "groupPolicyId",
"/networks/{networkId}/appliance/vlans": "vlanId",
"/devices/{serial}/switch/routing/interfaces": "interfaceId",
"/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces": "interfaceId",
"/networks/{networkId}/vlanProfiles": "iname",
"/devices/{serial}/switch/routing/staticRoutes": "staticRouteId",
"/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes": "staticRouteId",
"/devices/{serial}/switch/ports": "portID",
"/organizations/{organizationId}/admins": "id"
}
template_schemas = {
"/networks/{networkId}/wireless/ssids/{number}": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the SSID"
},
"enabled": {
"type": "boolean",
"description": "Whether or not the SSID is enabled"
}
}
}
}
def get_product_type(model):
for product_type, prefixes in PRODUCT_TYPES_MAP.items():
if any(model.startswith(prefix) for prefix in prefixes):
return product_type
return None
def org_admin_handler(path, api_key, base_url, payload, **kwargs):
event_handler("info", f"Org Admin Handler: {path}")
#
# See if we can figure out what this data structure using for its index
#
if isinstance(payload, list):
#
# First we need to see what data is there to see if we need to put or post
#
current_data = meraki_read_path(path, api_key, base_url, **kwargs)
current_data_by_name = {item['name']: item for item in current_data}
for item in payload:
if item["name"] in current_data_by_name:
event_handler("info", f"Updating admin user {item['name']}")
#
# The item exists, so we need to call the api's per-item form
#
item_path = path + '/{' + index_key + '}'
# Use the index_key from the current data instead of the imported data
kwargs["id"] = current_data_by_name[item["name"]]["id"]
result = meraki_write_path(item_path, args.api_key, base_url, item, api_handler=True, **kwargs)
else:
event_handler("info", f"Adding admin user {item['name']}")
#
# The item does not exist, so we create it with the same api
#
result = meraki_write_path(path, args.api_key, base_url, item, api_handler=True, **kwargs)
else:
# Cannot be procssed, return the payload
return (payload)
return ({})
def default_api_handler(path, api_key, base_url, payload, **kwargs):
event_handler("info", f"Default handler: {path}")
result = {}
index_key = None
#
# See if we can figure out what this data structure using for its index
#
if isinstance(payload, list):
#
# If this is a list, look to see if the index is known
#
if path in index_lookup:
index_key = index_lookup[path]
if index_key == None:
event_handler("error", f"Unable to process path {path}: Index not found.")
else:
#
# First we need to see what data is there to see if we need to put or post
#
data = meraki_read_path(path, api_key, base_url, **kwargs)
existing_data_map = {}
for item in data:
if "name" in item:
existing_data_map[item["name"]] = item
else:
event_handler("error", f"Unable to process path {path}: Name not found.")
return ({})
for item in payload:
if "radiusServers" in item:
for server in item["radiusServers"]:
server.pop("serverId", None)
server["secret"] = "ChangeMe"
if "radiusAccountingServers" in item:
for server in item["radiusAccountingServers"]:
server.pop("serverId", None)
server["secret"] = "ChangeMe"
if item["name"] in existing_data_map:
#
# The item exists, so we need to call the api's per-item form
#
item_path = path + '/{' + index_key + '}'
# Use the index_key from the current data instead of the imported data
kwargs[index_key] = existing_data_map[item["name"]][index_key]
result = meraki_write_path(item_path, args.api_key, base_url, item, **kwargs)
else:
#
# The item does not exist, so we create it with the same api
#
result = meraki_write_path(path, args.api_key, base_url, item, **kwargs)
else:
# Cannot be procssed, return the payload
return (payload)
return (result)
def noop(path, payload):
event_handler("warning", f"{path} is currently unsupported")
def wireless_handler(path, api_key, base_url, payload, **kwargs):
event_handler("info", f"Wireless hander: {path}")
# if payload["authMode"] == "psk":
# payload["psk"] = "ChangeMe"
if "radiusServers" in payload:
for server in payload["radiusServers"]:
server["secret"] = "ChangeMe"
if "openRoamingCertificateId" in server and server["openRoamingCertificateId"] == None:
server.pop("openRoamingCertificateId")
if "radiusAccountingServers" in payload:
for server in payload["radiusAccountingServers"]:
server["secret"] = "ChangeMe"
if "splashUrl" in payload and payload["splashUrl"] == None:
payload = {}
return (payload)
def switchport_handler(path, api_key, base_url, payload, **kwargs):
event_handler("info", f"Switchport hander: {path}")
for item in payload and item["profile"]["enabled"] == True:
if "profile" in item:
# The API does not allow certain attributes when assocaited with a port profile
if args.ignore_profile:
item["profile"]["enabled"] = False
else:
item.pop("tags", None)
item.pop("accessPolicyNumber", None)
item.pop("accessPolicyType", None)
item.pop("allowedVlans", None)
item.pop("daiTrusted", None)
item.pop("name", None)
item.pop("poeEnabled", None)
item.pop("rstpEnabled", None)
item.pop("stpGuard", None)
item.pop("type", None)
item.pop("udld", None)
item.pop("vlan", None)
item.pop("voiceVlan", None)
item.pop("isolationEnabled", None)
item_path = f"{path}/{item['portId']}"
verb, schema, responses = get_schema(path + "/{portId}", "write", **kwargs)
kwargs['portId'] = item['portId']
kwargs['schema'] = schema
kwargs['verb'] = verb
result = meraki_write_path(item_path, api_key, base_url, item, **kwargs)
return (result)
def switch_acl_handler(path, api_key, base_url, payload, **kwargs):
event_handler("debug", "Called switch_acl_handler")
new_payload = {
"rules": []
}
#
# Need to remove the default rule
#
for rule in payload["rules"]:
if rule["comment"] != "Default rule":
new_payload["rules"].append(rule)
return (new_payload)
def l3FirewallRules_handler(path, api_key, base_url, payload, **kwargs):
event_handler("debug", "Called switch_acl_handler")
new_payload = {
"rules": [],
"allowLanAccess": True
}
#
# Need to remove the default rule
#
for rule in payload["rules"]:
if rule["comment"] == "Wireless clients accessing LAN":
if rule["policy"] == "deny":
new_payload["allowLanAccess"] = False
elif rule["comment"] == "Default rule":
pass
else:
new_payload["rules"].append(rule)
return (new_payload)
api_path_handlers = {
"/networks/{networkId}/wireless/ssids/{number}": wireless_handler,
"/networks/{networkId}/wireless/ssids/{number}/splash/settings": wireless_handler,
"/networks/{networkId}/wireless/ssids/{number}/firewall/l3FirewallRules": l3FirewallRules_handler,
"/networks/{networkId}/switch/accessControlLists": switch_acl_handler,
"/organizations/{organizationId}/admins": org_admin_handler
# "/devices/{serial}/switch/ports": switchport_handler,
# "/networks/{networkId}/switch/accessPolicies": default_api_handler,
# "/networks/{networkId}/groupPolicies": default_api_handler,
# "/networks/{networkId}/appliance/vlans": default_api_handler,
# "/devices/{serial}/switch/routing/interfaces": default_api_handler,
# "/networks/{networkId}/vlanProfiles": default_api_handler,
# "/devices/{serial}/switch/routing/staticRoutes": default_api_handler,
# "/networks/{networkId}/wireless/ssids/{number}/splash/settings": noop,
# "/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces": default_api_handler,
# "/networks/{networkId}/switch/stacks/{switchStackId}/routing/staticRoutes": default_api_handler,
# "/networks/{networkId}/snmp": noop,
# "/networks/{networkId}/wireless/electronicShelfLabel": noop,
# "/devices/{serial}/wireless/electronicShelfLabel": noop,
# "/networks/{networkId}/webhooks/payloadTemplates": noop,
# "/devices/{serial}/appliance/dhcp/subnets": default_api_handler,
# "/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces/{interfaceId}/dhcp": noop,
# "/devices/{serial}/switch/routing/interfaces/{interfaceId}/dhcp": noop,
# "/networks/{networkId}/wireless/rfProfiles": noop,
# "/networks/{networkId}/wireless/ssids/{number}/splash/settings": noop,
# "/networks/{networkId}/wireless/ssids/{number}/hotspot20": noop
}
def get_spec_path(path):
if path in openapi_spec['paths']:
event_handler("debug", f"Found {path} in spec")
return path
else:
event_handler("debug", f"Finding match for {path} in spec")
# Sort keys by length in descending order to match the longest path first
sorted_keys = sorted(index_lookup.keys(), key=len, reverse=True)
new_path = None
for key in sorted_keys:
if path.startswith(key):
event_handler("debug", f"Found {key} as best match for {path}.")
# Get the value from index_lookup for the matched key
index = index_lookup[key]
# Create a regex pattern to identify the portion to be replaced
key_with_param = re.sub(r'\{[^}]+\}', '[^/]+', key) + r'/([^/]+)'
# Replace the first path component after the match with the placeholder value
new_path = re.sub(key_with_param, key + r'/{' + index + r'}', path)
break
# Return the original path if no match is found
if new_path:
return get_spec_path(new_path)
else:
event_handler("error", f"Could not find match for {path}")
return None
def get_schema(spec_path, operation, **kwargs):
spec_path_data = openapi_spec['paths'][spec_path]
if operation == 'write':
if 'put' in spec_path_data:
verb = 'put'
schema = spec_path_data[verb]["requestBody"]["content"]["application/json"]["schema"]
responses = [int(item) for item in spec_path_data[verb]["responses"].keys()]
elif 'post' in spec_path_data:
verb = 'post'
if "requestBody" in spec_path_data[verb]:
schema = spec_path_data[verb]["requestBody"]["content"]["application/json"]["schema"]
else:
schema = {}
responses = [int(item) for item in spec_path_data[verb]["responses"].keys()]
else:
event_handler("warning", f"{path}, Error: Readonly path")
verb = None
schema = {}
elif operation == 'read':
if 'get' in spec_path_data:
verb = 'get'
schema = {}
responses = [int(item) for item in spec_path_data[verb]["responses"].keys()]
else:
event_handler("debug", f"{spec_path} is a write-only path")
verb = None
schema = {}
responses = {}
else:
event_handler("critical", f"Unknown schema operation {operation}.")
exit (1)
if "bound_to_template" in kwargs and kwargs["bound_to_template"] == True:
#
# If this is for a template, we override the template schema, but keep the verb
if spec_path in template_schemas:
schema = template_schemas[spec_path]
else:
schema = {}
return (verb, schema, responses)
def is_invalid_payload(data, schema):
try:
validate(instance=data, schema=schema)
return None
except jsonschema.exceptions.ValidationError as err:
return err.message
def remove_null_values(d):
# Create a copy of the dictionary to avoid modifying the original during iteration
keys_to_delete = []
for key, value in d.items():
if isinstance(value, dict):
# Recurse into the nested dictionary
remove_null_values(value)
# If the nested dictionary is empty after recursion, mark the key for deletion
if not value:
keys_to_delete.append(key)
elif value is None:
# Mark keys with null values for deletion
keys_to_delete.append(key)
# Remove keys marked for deletion
for key in keys_to_delete:
del d[key]
def meraki_request(url, api_key, verb="get", responses=[200], payload={}, parameters=[], **kwargs):
headers = {
'Authorization': f'Bearer {api_key}'
}
while True:
try:
if verb == "get":
parameter_string = ""
for parameter in parameters:
if parameter_string == "":
parameter_string = '?' + parameter
else:
parameter_string = parameter_string + '&' + parameter
response = requests.get(url + parameter_string,
headers = headers,
timeout = (API_CONNECT_TIMEOUT, API_TRANSMIT_TIMEOUT)
)
elif verb == "put":
response = requests.put(url,
headers = headers,
json = payload,
timeout = (API_CONNECT_TIMEOUT, API_TRANSMIT_TIMEOUT)
)
else:
response = requests.post(url,
headers = headers,
json = payload,
timeout = (API_CONNECT_TIMEOUT, API_TRANSMIT_TIMEOUT)
)
# Check the status code
if response.status_code in responses:
if response.status_code == 204:
return {}
else:
return (response.json())
# elif response.status_code == 401:
# event_handler("critical", f"{url}, Error 401: Unauthorized access - check your API key.")
# exit (1)
# elif response.status_code == 404:
# event_handler("critical", f"{url}, Error 404: The requested resource was not found.")
# exit (1)
elif response.status_code == 429:
retry_after = response.headers.get("Retry-After")
if retry_after is not None:
wait_retry = int(retry_after)
else:
wait_retry = API_RETRY_DEFAULT_WAIT
event_handler("warning", f"Error 429: Rate limit exceeded. Retrying in {wait_retry} seconds...")
time.sleep(wait_retry)
else:
event_handler("error", f"{url}, Error {response.status_code} ({response.reason}): {response.text}")
return None
except requests.exceptions.RequestException as e:
event_handler("critical", f"An error occurred while making the request: {e}")
exit (1)
def meraki_read_path(path, api_key, base_url, **kwargs) -> dict | None:
# Get the spec path that corresponds to this path
spec_path = get_spec_path(path)
if spec_path == None:
event_handler("error", f"Could not find {path} in spec.")
return (None)
if 'schema' in kwargs:
schema = kwargs['schema']
verb = 'get'
else:
verb, schema, responses = get_schema(spec_path, "read", **kwargs)
url = f"{base_url}" + path.format(**kwargs).removesuffix('/')
if verb == None:
event_handler("debug", f"{path} is write-only")
return None
return meraki_request(url, api_key, responses=responses, **kwargs)
def meraki_write_path(path, api_key, base_url, raw_payload, api_handler=False, **kwargs) -> dict | None:
change_needed = True
path = path.removesuffix('/')
# Get the spec path that corresponds to this path
spec_path = get_spec_path(path)
if spec_path == None:
event_handler("error", f"Could not find {path} in spec.")
return (None)
if 'schema' in kwargs:
schema = kwargs['schema']
verb = kwargs['verb']
else:
verb, schema, responses = get_schema(spec_path, "write", **kwargs)
full_path = path.format(**kwargs)
url = f"{base_url}" + full_path
if "bound_to_template" in kwargs and kwargs["bound_to_template"] == True and schema == {}:
event_handler("info", f"Network {kwargs['networkId']} is bound to a template. Ignoring {full_path}")
return {}
# See if we need a special handler for this path
if spec_path in api_path_handlers:
processed_payload = api_path_handlers[spec_path](path, api_key, base_url, raw_payload, **kwargs)
else:
processed_payload = raw_payload
# Reduce the payload down to what is in the schema for the put/post operation
filtered_payload = filter_data_by_schema(processed_payload, schema)
if hasattr(args, 'diff') and args.diff == True and not api_handler:
show_diff = True
else:
show_diff = False
#
# Get the current data
#
current_data = meraki_read_path(path, args.api_key, base_url, **kwargs)
if (current_data != None):
write_only_url = False
filtered_current_data = filter_data_by_schema(current_data, schema)
#
# Diff the current state and the proposed state
#
diff_dict = list(diff(filtered_current_data, filtered_payload))
else:
write_only_url = True
diff_dict = []
event_handler("debug", f"Unable to get path {full_path}")
# filtered_payload = remove_null_values(filtered_payload)
if processed_payload and (diff_dict or write_only_url):
change_needed = True
if show_diff:
print(color_message(path.format(**kwargs), "yellow"))
if not write_only_url:
# print ("Current:")
# pprint.pp(filtered_current_data)
# print ("New:")
# pprint.pp(filtered_payload)
# print ("Diff:")
pprint.pp(diff_dict)
else:
change_needed = False
if show_diff:
print(color_message(path.format(**kwargs), "green"))
if args.dry_run or (filtered_payload == {} and schema != {}):
change_needed = False
# Override the diff and always write the data
if hasattr(args, 'always_write') and args.always_write == True:
change_needed = True
if change_needed:
# if args.log_level == "DEBUG":
return meraki_request(url, api_key, payload=processed_payload, verb=verb, responses=responses, **kwargs)
else:
return {}
async def merakiBulkGet(session, path, api_key, base_url, semaphore):
"""
Fetches the content of the URL using a GET request with headers.
Parameters:
- session (aiohttp.ClientSession): The aiohttp session.
- url (str): The URL to fetch.
- headers (dict): The headers to include in the request.
- path (str): The API path to structure the results.
- semaphore (asyncio.Semaphore): The semaphore to limit concurrent requests.
Returns:
- tuple: A tuple containing the path and its response.
"""
headers = {
'Authorization': f'Bearer {api_key}'
}
url = f"{base_url}" + path
retry = 0
async with semaphore:
while True:
try:
async with session.get(url, headers=headers) as response:
if response.status == 200:
if response.headers['Content-Type'] == 'application/json':
return (path, await response.json())
else:
return (path, await response.json(encoding="utf-8"))
elif response.status == 429:
retry_after = response.headers.get("Retry-After")
if retry_after is not None:
wait_retry = int(retry_after)
else:
wait_retry = API_RETRY_DEFAULT_WAIT
event_handler("debug", f"Received {response.status} status code. Retrying url {url} in {wait_retry} seconds...")
elif response.status in [400, 404]:
event_handler("error", f"{url}, Error {response.status} ({response.reason})")
return (path, {})
else:
event_handler("error", f"{url}, Error {response.status} ({response.reason}): {response.text}")
return (path, {})
retry = retry + wait_retry
await asyncio.sleep(retry)
except aiohttp.ClientError as e:
event_handler("error", f"An error occurred: {str(e)}")
except asyncio.TimeoutError:
event_handler("error", "The request timed out.")
except Exception as e:
event_handler("error", f"An unexpected error occurred: {str(e)}")
async def fetch_all_paths(paths, headers, base_url, max_concurrent_requests):
"""
Fetches the content of all URLs asynchronously with headers, limiting concurrent requests.
Parameters:
- urls (list): A list of tuples containing URLs and paths to fetch.
- headers (dict): The headers to include in the request.
- max_concurrent_requests (int): The maximum number of concurrent requests allowed.
Returns:
- dict: A dictionary containing all paths and their responses.
"""
semaphore = asyncio.Semaphore(max_concurrent_requests)
async with aiohttp.ClientSession() as session:
tasks = [merakiBulkGet(session, path, headers, base_url, semaphore) for path in paths]
result_dict = {}
for task in asyncio.as_completed(tasks):
# as_completed returns an iterator, so we just have to await the iterator and not call it
(path, result) = await task
match = re.match('^/([^/]+)/([^/]+)(/[^{}]*)?$', path)
if result:
if match.group(1) not in result_dict:
result_dict[match.group(1)] = {}
if match.group(2) not in result_dict[match.group(1)]:
result_dict[match.group(1)][match.group(2)] = {}
result_dict[match.group(1)][match.group(2)]['paths'] = {}
result_dict[match.group(1)][match.group(2)]['paths'][match.group(3)] = result
return result_dict
def filter_data_by_schema(data, schema):
"""Recursively filters the data to match the structure defined by the schema."""
if 'properties' in schema:
filtered_data = {}
for key, subschema in schema['properties'].items():
if key in data:
filtered_data[key] = filter_data_by_schema(data[key], subschema)
return filtered_data
elif 'items' in schema and isinstance(data, list):
return [filter_data_by_schema(item, schema['items']) for item in data]
else:
return data
def print_tabular_data(data, columns_to_display, sort_by=None, ascending=True):
"""
Formats and prints JSON-like data in a tabular format with left-justified headers and data.
Args:
data (list of dict): The input data to be formatted and printed.
columns_to_display (list of str): The columns to be printed.
"""
# Convert the list of dictionaries to a pandas DataFrame
df = pd.DataFrame(data)
# Sort the DataFrame by the specified column if provided
if sort_by:
df = df.sort_values(by=sort_by, ascending=ascending)
# Calculate the max width for each column to apply uniform left-justification
max_col_widths = {col: max(df[col].astype(str).map(len).max(), len(col)) for col in columns_to_display}
# Left-justify column titles and data with custom formatting
formatted_rows = []
# Format the header row
header_row = ' '.join([col.ljust(max_col_widths[col]) for col in columns_to_display])
formatted_rows.append(header_row)
# Format the data rows
for _, row in df[columns_to_display].iterrows():
formatted_row = ' '.join([str(row[col]).ljust(max_col_widths[col]) for col in columns_to_display])
formatted_rows.append(formatted_row)
# Print the formatted table
print('\n'.join(formatted_rows))
def print_csv_data(data, columns, sort_by=None, ascending=True):
# Convert the list of dicts to a DataFrame
df = pd.DataFrame(data, columns=columns)
# Alternatively, you can save the CSV to a file
if args.output_file:
output_file = args.output_file
df.to_csv(output_file, index=False)
else:
print(df.to_csv(index=False))
async def export_command(args):
#
# Build the list of paths that we want to export
#
api_paths = []
network_ids = []
serial_numbers = []
config_template_ids = []
stacks_by_network = {}
parameters = []
serial_parameters = []
if args.network_ids:
network_ids = args.networks
for network_id in network_ids:
parameters.append(f"networkIds[]={network_id}")
networks = meraki_read_path("/organizations/{organizationId}/networks", args.api_key, args.base_url, organizationId=args.org_id, parameters=parameters)
serial_parameters = parameters
elif args.tags:
parameters = ['tagsFilterType=withAnyTags']
for tag in args.tags:
parameters.append(f"tags[]={tag}")
networks = meraki_read_path("/organizations/{organizationId}/networks", args.api_key, args.base_url, organizationId=args.org_id, parameters=parameters)
for network in networks:
serial_parameters.append(f"networkIds[]={network['id']}")
elif args.networks:
networks = []
# Create a dict of networks by name
network_list = meraki_read_path("/organizations/{organizationId}/networks", args.api_key, args.base_url, organizationId=args.org_id)
networks_by_name = {network['name']: network for network in network_list}
# Find matches and retrieve their networkId
for network_name in args.networks:
for key in networks_by_name.keys():
if network_name in key:
networks.append(networks_by_name[key])
network_id = networks_by_name[key].get('id')
serial_parameters.append(f"networkIds[]={network_id}")
network_ids.append(network_id)
# if network_ids:
# networks = []
# template_ids =[]
# for network_id in network_ids:
# network = meraki_read_path("/networks/{networkId}", args.api_key, args.base_url, networkId=network_id)
# networks.append(network)
# parameters.append(f"networkIds[]={network_id}")
# #
# # Collect the config templates that the networks are bound to
# #
# if "isBoundToConfigTemplate" in network and network["isBoundToConfigTemplate"] == True:
# if network["configTemplateId"] not in template_ids:
# template_ids.append(network["configTemplateId"])
# network_ids.extend(template_ids)
else:
event_handler("info", f"Exporting all networks for organization {args.org_id}")
networks = meraki_read_path("/organizations/{organizationId}/networks", args.api_key, args.base_url, organizationId=args.org_id)
# List comprehension to extract serial numbers
network_ids = [item["id"] for item in networks]
#
# Get all of the templates for export
#
config_template_templates = meraki_read_path("/organizations/{organizationId}/configTemplates", args.api_key, args.base_url, organizationId=args.org_id)
# List comprehension to extract serial numbers
network_ids = network_ids + [item["id"] for item in config_template_templates]
event_handler("info", f"Exporting networks/templates {network_ids}")
#
# Get all of the devices for export
#
devices = meraki_read_path("/organizations/{organizationId}/devices", args.api_key, args.base_url, organizationId=args.org_id, parameters=serial_parameters)
# List comprehension to extract serial numbers
serial_numbers = [item["serial"] for item in devices]
for network in networks:
if "switch" in network["productTypes"]:
#
# Get all of the switch stacks for export
#
switch_stacks = meraki_read_path("/networks/{networkId}/switch/stacks", args.api_key, args.base_url, networkId=network["id"])
if switch_stacks:
stacks_by_network[network["id"]] = {}
for stack in switch_stacks:
switch_stacks_interfaces = meraki_read_path("/networks/{networkId}/switch/stacks/{switchStackId}/routing/interfaces", args.api_key, args.base_url, networkId=network["id"], switchStackId=stack["id"])
stack_interface_ids = []
for interface in switch_stacks_interfaces:
stack_interface_ids.append(interface["interfaceId"])
stacks_by_network[network["id"]][stack["id"]] = stack_interface_ids
#
# Find all of the paths out of the spec that apply to what we are trying to export
#
for path, verbs in openapi_spec['paths'].items():
# Only get paths that we can write something back to.
path_exported = False
if path in config["api_path_exlude"]:
event_handler("debug", f"{path} is excuded")
continue
elif 'get' not in verbs.keys():
event_handler("debug", f"{path} is write-only")
continue
elif (len(verbs) == 1 and "get" in verbs) and not (args.full and path in readonly_exceptions):
event_handler("debug", f"{path} is read-only")
continue
else:
get_tags = verbs['get']['tags']
#
# /networks/{networkId}: We need to itterate over all of the networks
#
if match := re.match('^/networks/{networkId}/?(.*)$', path):
if args.contexts and not 'networks' in args.contexts:
continue
base_path = "/networks/{networkId}"
sub_path = "/" + match.group(1)
for network in networks:
network_id = network["id"]
# Check to see if this path is approriete for this network
if (not 'networks' in get_tags) and (not bool(set(network["productTypes"]) & set(get_tags))):
event_handler("debug", f"Skipping {path} for {network['name']}: {network['productTypes']}")
continue
#
# Wireless SSIDS
#
if match := re.match('^/wireless/ssids/{number}(/.*)?$', sub_path):
if match.group(1):
wireless_path = match.group(1)
else:
wireless_path = ""
if match := re.match('^/[^{}]+{', wireless_path):
# Unhandled paths because they need more dereferencing
path_exported = False
else:
path_exported = True
# We need to have one of each of these paths per device
for number in range(0, 14):
api_paths.append(f"/networks/{network_id}/wireless/ssids/{number}" + wireless_path)
#
# Switch Stacks
#
elif match := re.match('^/switch/stacks/{switchStackId}(/.+)?$', sub_path):
if network_id not in stacks_by_network:
# There are no stacks
continue
if match.group(1):
stack_path = match.group(1)
else:
stack_path = ""
if match := re.match('^/[^{}]+{', stack_path):
# Unhandled paths because they need more dereferencing
path_exported = False
else:
path_exported = True
# We need to have one of each of these paths per device
for stack_id, stack_interfaces in stacks_by_network[network_id].items():
if match := re.match('^/routing/interfaces/{interfaceId}(/.*)?$', stack_path):
if match.group(1):
if match.group(1) == "/dhcp":
for interface_id in stack_interfaces:
api_paths.append(f"/networks/{network_id}/switch/stacks/{stack_id}/routing/interfaces/{interface_id}/dhcp")
else:
api_paths.append(f"/networks/{network_id}/switch/stacks/{stack_id}/routing/interfaces/{interface_id}" + match.group(1))
else:
api_paths.append(f"/networks/{network_id}/switch/stacks/{stack_id}" + stack_path)
elif match := re.match('^/[^{}]+{', sub_path):
# Unhandled paths because they need more dereferencing
path_exported = False
else:
path_exported = True
api_paths.append(f"/networks/{network_id}" + sub_path)
#
# /organizations/{args.org_id}
#
elif match := re.match('^/organizations/{organizationId}/?(.*)$', path):
sub_path = '/' + match.group(1)
if match := re.match('^/[^{}]+{', sub_path):
# Unhandled paths because they need more dereferencing
path_exported = False
else:
path_exported = True
api_paths.append(f"/organizations/{args.org_id}" + sub_path)
#
# /devices/{serial}
#
elif match := re.match('^/devices/{serial}/?(.*)$', path):
if args.contexts and not 'devices' in args.contexts:
continue
sub_path = '/' + match.group(1)
if match := re.match('^/[^{}]+{', sub_path):
# Unhandled paths because they need more dereferencing
path_exported = False
elif devices:
path_exported = True
# We need to have one of each of these paths per device
for device in devices:
device_type = get_product_type(device["model"])
if sub_path == "/" or device_type in get_tags:
api_paths.append(f"/devices/{device['serial']}" + sub_path)
#
# "/devices/{serial}/switch/routing/interfaces/{interfaceId}"
#
if not path_exported:
event_handler("warning", f"{path} not exported")
#
# Make a bulk request to the async function
#
result_dict = await fetch_all_paths(api_paths, args.api_key, args.base_url, args.max_concurrent_requests)
if args.output_file:
output_file = args.output_file
else:
if args.networks and len(args.networks) == 1:
output_file = f"{args.org_id}_{args.networks[0]}.json"
else:
output_file = f"{args.org_id}.json"
with open(output_file, 'w') as file:
result_dict['errors'] = error_log
json.dump(result_dict, file, indent=4)
event_handler("info", f"Results saved to {output_file}")
def import_file(filename):
event_handler("info", f"Reading {filename}...")
try:
with open(filename, 'r') as file:
if filename.endswith('json'):
return json.load(file)
else:
return yaml.safe_load(file)
except FileNotFoundError:
event_handler("critical", f"Error: The file '{args.input_file}' was not found.")
exit (1)
except json.JSONDecodeError:
event_handler("critical", f"Error: The file '{args.input_file}' contains invalid JSON.")
exit (1)
except PermissionError:
event_handler("critical", f"Error: You do not have permission to read the file '{args.input_file}'.")
exit (1)
except Exception as e:
event_handler("critical", f"An unexpected error occurred: {str(e)}")
exit (1)
def export_file(filename, contents):
event_handler("info", f"Writing {filename}...")
with open(filename, 'w') as file:
json.dump(contents, file, indent=4)
def show_command(args):
parameters = []
# For the show commands, we are going to use the meraki python library to get the data
# because it makes it a bit easeier and we do not have to worry about the API paths
# not being there.
dashboard = meraki.DashboardAPI(api_key=args.api_key, base_url=args.base_url, inherit_logging_config=True, output_log=False)
if hasattr(args, 'tags') and args.tags:
for tag in args.tags:
parameters.append(f"tags[]={tag}")
if args.show_command == 'networks':
# If a data file is provided, use that data instead of making an API call
if args.input_file:
import_data = import_file(args.input_file)
networks = []
for network_id, network_data in import_data["networks"].items():
if "/" in network_data["paths"]:
networks.append(network_data["paths"]["/"])
else:
networks = meraki_read_path("/organizations/{organizationId}/networks", args.api_key, args.base_url, organizationId=args.org_id)
if args.json:
pprint.pp(networks)
else:
print_tabular_data(networks, ['name', 'id', 'productTypes', 'timeZone', 'tags'], sort_by='name')
elif args.show_command == 'organizations':
organizations = dashboard.organizations.getOrganizations()
if args.json:
pprint.pp(organizations)
else:
print_tabular_data(organizations, ['id', 'name'])
elif args.show_command == 'devices':
# If a data file is provided, use that data instead of making an API call
if args.input_file:
import_data = import_file(args.input_file)
source_org_id = next(iter(import_data["organizations"]))
networks = import_data["organizations"][source_org_id]["paths"]["/networks"]
networks_by_id = {network['id']: network for network in networks}
devices = []
for serial, device_data in import_data["devices"].items():
if "/" in device_data["paths"]:
device = device_data["paths"]["/"]
if device["networkId"] in networks_by_id:
device["network"] = networks_by_id[device["networkId"]]["name"]
else:
device["network"] = device["networkId"]
devices.append(device)
else:
kwargs = {}
if args.serial:
kwargs["serial"] = args.serial
# devices = meraki_read_path("/organizations/{organizationId}/devices", args.api_key, args.base_url, organizationId=args.org_id)
devices = dashboard.organizations.getOrganizationDevices(args.org_id, total_pages='all', **kwargs)
# networks = meraki_read_path("/organizations/{organizationId}/networks", args.api_key, args.base_url, organizationId=args.org_id)
networks = dashboard.organizations.getOrganizationNetworks(args.org_id, total_pages='all')
networks_by_id = {network['id']: network for network in networks}
# Get the devices status
devices_statuses = dashboard.organizations.getOrganizationDevicesStatuses(args.org_id, total_pages='all')
devices_statuses_by_serial = {device_status['serial']: device_status for device_status in devices_statuses}
#
# Convert Network ID to Network Name
#
for device in devices:
if device["networkId"] in networks_by_id:
device["network"] = networks_by_id[device["networkId"]]["name"]
else:
device["network"] = device["networkId"]
if device["serial"] in devices_statuses_by_serial:
device["status"] = devices_statuses_by_serial[device["serial"]]["status"]
else:
device["status"] = "Unknown"