-
Notifications
You must be signed in to change notification settings - Fork 0
/
guest_grabber.py
422 lines (370 loc) · 17.1 KB
/
guest_grabber.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
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
#!/bin/python3
########################################################################################################################
# Guest Grabber - Get historical authorized guests 0from a specified Mist org via API
#
# This work is licensed under the Mozilla Public License 2.0
########################################################################################################################
# Author: Ryan M. Adzima & Jake Snyder
# Copyright: Copyright 2021, Juniper Networks & Ryan M. Adzima
# License: MIT
# Version: 1.0.0
# Maintainer: Ryan M. Adzima & Jake Snyder
# Email: [email protected]
# Status: Best-effort
########################################################################################################################
import sys
from datetime import datetime, timezone
import csv
from pprint import pprint
import requests
import logging
import json
OUTPUT_PATH = "./guests.csv" # Change this to the location to write the new CSV file (relative or absolute)
TIME_FORMAT = "%I:%M:%S %m-%d-%Y" # Datetime format, change to your preference
# TODO: Create CLI flags and/or config file methods to avoid hard-coding tokens and UUIDs
API_TOKEN = "YOUR API TOKEN HERE" # https://api.mist.com/api/v1/self/apitokens
ORG_ID = "YOUR ORG_ID HERE" # Org ID to get sites *** NOT IMPLEMENTED YET ***
ENV = "api.mist.com"
### DON'T CHANGE THE VALUES BELOW UNLESS ABSOLUTELY NECCESSARY ###
HEADERS = { # HTTP headers for interacting with the Mist API
"Authorization": f"Token {API_TOKEN}", # API token converted to an authorization header
"Content-type": "application/json" # Specify the content type (JSON) just in case
}
class MistCredentials(object):
def __init__(self, org_id: str, apitoken: str, env: str = "api.mist.com"):
self.org_id = org_id
self.apitoken = apitoken
self.env = env
class MistOrg(object):
def __init__(self, creds: MistCredentials):
import requests
self.org_id = creds.org_id
self.apitoken = creds.apitoken
self.host = creds.env
def check_authentication(self):
import requests
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/self"
response = requests.get(url, headers=headers)
if response.status_code == 200:
return True
else:
logging.error(f"Auth Failed: {response.text}")
return False
def get_sites(self):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/orgs/{self.org_id}/sites"
response = requests.get(url, headers=headers)
if response.status_code == 200:
self.sites = response.json()
return response.json()
else:
return None
def search_site_switchports(self, site_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/stats/ports/search"
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return None
def search_site_guest_authorizations(self, site_id, duration="7d", limit=1000, wlan=False):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/guests/search?duration={duration}&limit={limit}"
if wlan != False:
url = url + f"&wlan={wlan}"
results = []
response = requests.get(url, headers=headers)
results = results + response.json()['results']
while "next" in response.json():
url = f"https://{self.host}{response.json()['next']}"
response = requests.get(url, headers=headers)
results = results + response.json()['results']
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def get_org_inventory(self, device_type: str = ""):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/orgs/{self.org_id}/inventory?type={device_type}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
self.sites = response.json()
return response.json()
else:
return None
def get_org_stats(self):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/orgs/{self.org_id}/stats"
response = requests.get(url, headers=headers)
if response.status_code == 200:
self.sites = response.json()
return response.json()
else:
return None
def get_device_stats(self, device_id, site_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/stats/devices/{device_id}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
self.sites = response.json()
return response.json()
else:
return None
def get_site_webhooks(self, site_id: str):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/webhooks"
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return None
def get_site_insight_metric(self, site_id, scope, scope_id, metric):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/insights/{scope}/{scope_id}/{metric}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return None
def get_device_switchport_stats(self, site_id, mac):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/stats/switch_ports/search?mac={mac}"
results = []
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = results + response.json()['results']
while "next" in response.json():
url = f"https://{self.host}{response.json()['next']}"
response = requests.get(url, headers=headers)
results = results + response.json()['results']
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def search_device_switchport_search(self, site_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/stats/switch_ports/search"
results = []
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = results + response.json()['results']
while "next" in response.json():
url = f"https://{self.host}{response.json()['next']}"
response = requests.get(url, headers=headers)
results = results + response.json()['results']
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def get_org_network_templates(self):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/orgs/{self.org_id}/networktemplates"
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def get_site_setting(self, site_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/setting"
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def get_site_info(self, site_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def get_site_maps(self, site_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/maps"
response = requests.get(url, headers=headers)
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def get_site_map(self, site_id, map_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/maps/{map_id}"
response = requests.get(url, headers=headers)
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def get_site_devices(self, site_id):
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = f"https://{self.host}/api/v1/sites/{site_id}/devices"
response = requests.get(url, headers=headers)
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def upload_site_map_image(self, site_id, map_id, filename):
headers = {"Authorization": f"token {self.apitoken}", 'Accept': 'application/json'}
url = f"https://{self.host}/api/v1/sites/{site_id}/maps/{map_id}/image"
#payload = {'json': '{}'}
files = [
('file', (str(filename),
open(filename, 'rb'), 'image/png'))
]
response = requests.post(url, headers=headers, files=files)
if response.status_code == 200:
results = response.json()
return results
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def clone_site_map(self, site_id: str, map_data: dict):
import copy
import shutil
headers = {"Content-Type": "application/json", "Authorization": f"token {self.apitoken}"}
url = url = f"https://{self.host}/api/v1/sites/{site_id}/maps"
data = copy.deepcopy(map_data)
for item in ['id', 'site_id', 'org_id', 'created_time', 'modified_time', 'url', 'thumbnail_url']:
data.pop(item)
image_response = requests.get(map_data['url'], stream=True)
image_response.raw.decode = True
image_data = image_response.raw
image_name = map_data['url'].split("/")[-1].split('?')[0]
with open(image_name, 'wb') as f:
shutil.copyfileobj(image_response.raw, f)
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
new_map_data = response.json()
map_upload = self.upload_site_map_image(site_id, new_map_data['id'], image_name)
if map_upload is not None:
final_response = self.get_site_map(site_id, new_map_data['id'])
return final_response
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
else:
print(f"URL: {url}")
print(f"Response Code: {response.status_code}")
print(response.text)
return None
def write_guests(guest_list: list, output: str):
"""
Writes guest data to the file specified in the 'OUTPUT_PATH' variable
:param str output: Location where the new CSV file should be written (relative or absolute)
:param list guest_list: List containing the formatted guest data
"""
cols = []
for guest in guest_list:
for key in guest.keys():
if key not in cols:
cols.append(key)
#cols = ["Name", "Email", "Auth Time", "Expire Time", "Client MAC", "SSID", "AP Name", "AP MAC"]
try:
with open(output, 'w') as guest_csv:
writer = csv.DictWriter(guest_csv, fieldnames=cols, extrasaction='ignore')
writer.writeheader()
writer.writerows(guest_list)
except csv.Error as e:
print(f"CSV library exception while attempting to write CSV file: {e}")
raise e
except (FileExistsError, FileNotFoundError, IOError) as e:
print(f"Filesystem or IO exception while attempting to write CSV data to output file '{output}': {e}")
raise e
except (OSError, SystemError) as e:
print(f"System exception while attempting to write CSV file: {e}")
raise e
except Exception as e:
print(f"Unknown exception while attempting to write CSV file: {e}")
raise e
def ap_name_from_mac(auth: dict, inventory: list) -> str:
"""
Retrieves the name of the AP based on the provided MAC address to make the CSV more human-readable
:param dict auth: guest authorization
:param list inventory: Mist AP inventory output
:return dict: authorization with ap_name added.
"""
mac = auth.get('ap', None)
devices = []
if mac is not None:
devices = [device['name'] for device in inventory if device['mac'] == mac]
if len(devices) == 1:
auth['ap_name'] = devices[0]
return auth
def time_update(auth):
auth["Auth Time"] = datetime.utcfromtimestamp(auth['authorized_time']).replace(tzinfo=timezone.utc).astimezone(
tz=None).strftime(TIME_FORMAT)
auth["Expire Time"] = datetime.utcfromtimestamp(auth['authorized_expiring_time']).replace(tzinfo=timezone.utc).astimezone(
tz=None).strftime(TIME_FORMAT)
return auth
def guest_grabber():
"""
Main worker function for guest grabber script
"""
my_creds = MistCredentials(org_id=ORG_ID, apitoken=API_TOKEN, env=ENV)
my_org = MistOrg(my_creds)
inventory = my_org.get_org_inventory()
try:
# TODO: Be less ugly at providing feedback to the user
site_data = my_org.get_sites()
guest_data = []
for site in site_data:
guest_auths = my_org.search_site_guest_authorizations(site['id'])['results']
guest_data = guest_data + guest_auths
guest_data = [ap_name_from_mac(auth, inventory) for auth in guest_data]
guest_data = [time_update(auth) for auth in guest_data]
print("Guest Data")
pprint(guest_data)
#guests_data = get_guest_logins(site_id=ORG_ID)
#print(f"Got {len(guests_data)} records.")
#print("Formatting guest data...")
#guests_formatted = format_guests(guest_list=guests_data, site_id=SITE_ID)
#print(f"Formatted {len(guests_formatted)} records.")
#print(f"Writing data to CSV file {OUTPUT_PATH}...")
write_guests(guest_list=guest_data, output=OUTPUT_PATH)
#print(f"Wrote CSV file to {OUTPUT_PATH}.")
except KeyboardInterrupt:
print("User cancelled, exiting.")
print("Done.")
sys.exit(0)
if __name__ == '__main__':
guest_grabber()