-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdnacenter_create_report_webhook.py
445 lines (407 loc) · 15.9 KB
/
dnacenter_create_report_webhook.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately in
writing, software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
"""
__author__ = "Gabriel Zapodeanu TME, ENB"
__email__ = "gzapodea@cisco.com"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2021 Cisco and/or its affiliates."
__license__ = "Cisco Sample Code License, Version 1.1"
import datetime
import logging
import os
import time
import urllib3
import json
import requests
from datetime import datetime
from dotenv import load_dotenv
from requests.auth import HTTPBasicAuth # for Basic Auth
from urllib3.exceptions import InsecureRequestWarning # for insecure https warnings
load_dotenv('environment.env')
DNAC_URL = os.getenv('DNAC_URL')
DNAC_USER = os.getenv('DNAC_USER')
DNAC_PASS = os.getenv('DNAC_PASS')
os.environ['TZ'] = 'America/Los_Angeles' # define the timezone for PST
time.tzset() # adjust the timezone, more info https://help.pythonanywhere.com/pages/SettingTheTimezone/
urllib3.disable_warnings(InsecureRequestWarning) # disable insecure https warnings
DNAC_AUTH = HTTPBasicAuth(DNAC_USER, DNAC_PASS)
REPORT_CATEGORY = 'Client'
VIEW_NAME = 'Client Detail'
WEBHOOK_NAME = 'LinuxMint_Report'
REPORT_NAME = 'Client Report Detail 24 hours'
WEBHOOK_DELIVERY = True
def pprint(json_data):
"""
Pretty print JSON formatted data
:param json_data: data to pretty print
:return None
"""
print(json.dumps(json_data, indent=4, separators=(', ', ': ')))
def get_dnac_jwt_token(dnac_auth):
"""
Create the authorization token required to access DNA C
:param dnac_auth - Cisco DNA Center Basic Auth string
:return: Cisco DNA Center JWT token
"""
url = DNAC_URL + '/dna/system/api/v1/auth/token'
header = {'content-type': 'application/json'}
response = requests.post(url, auth=dnac_auth, headers=header, verify=False)
dnac_jwt_token = response.json()['Token']
return dnac_jwt_token
def get_report_view_groups(dnac_auth):
"""
This function will return the report view groups
:param dnac_auth: Cisco DNA Center Auth
:return: report view groups
"""
url = DNAC_URL + '/dna/intent/api/v1/data/view-groups'
header = {'Content-Type': 'application/json', 'X-Auth-Token': dnac_auth}
response = requests.get(url, headers=header, verify=False)
report_view_groups = response.json()
return report_view_groups
def get_report_view_ids(view_group_id, dnac_auth):
"""
This function will get return the views for the groups id {view_group_id}
:param view_group_id: report view group id
:param dnac_auth: Cisco DNA Center Auth
:return: the report view ids
"""
url = DNAC_URL + '/dna/intent/api/v1/data/view-groups/' + view_group_id
header = {'Content-Type': 'application/json', 'X-Auth-Token': dnac_auth}
response = requests.get(url, headers=header, verify=False)
report_view_ids = response.json()
return report_view_ids
def get_detailed_report_views(view_id, group_id, dnac_auth):
"""
This function will retrieve the view details for the view group id {group_id} and the view id {view_id}
:param view_id: report view id
:param group_id: report group id
:param dnac_auth: Cisco DNA Center Auth
:return: the report report view details
"""
url = DNAC_URL + '/dna/intent/api/v1/data/view-groups/' + group_id + '/views/' + view_id
header = {'Content-Type': 'application/json', 'X-Auth-Token': dnac_auth}
response = requests.get(url, headers=header, verify=False)
report_detailed_views = response.json()
return report_detailed_views
def create_report(payload, dnac_auth):
"""
This function will create a new Client Detail report
:param payload: request payload
:param dnac_auth: Cisco DNA Center Auth
:return: return the API response
"""
url = DNAC_URL + '/dna/intent/api/v1/data/reports'
header = {'Content-Type': 'application/json', 'X-Auth-Token': dnac_auth}
response = requests.post(url, headers=header, data=json.dumps(payload), verify=False)
return response
def get_destination_by_name(webhook_name, dnac_auth):
"""
This function will return the REST (webhook) configuration for the {webhook_name}
:param webhook_name: webhook name for which we will get the configuration
:param dnac_auth: Cisco DNA Center Auth
:return: webhook details
"""
url = DNAC_URL + '/dna/intent/api/v1/event/subscription-details/rest?connectorType=REST&name=' + webhook_name
header = {'Content-Type': 'application/json', 'X-Auth-Token': dnac_auth}
response = requests.get(url, headers=header, verify=False)
response_json = response.json()
webhook_info = response_json[0]
return webhook_info
def main():
"""
This application will create a new Client Detail Report:
- for the Global site
- all client details
- run now schedule
- all client details
- wired and wireless clients
- report completion notification via Webhooks
"""
# logging, debug level, to file {application_run.log}
logging.basicConfig(
filename='application_run.log',
level=logging.DEBUG,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
current_time = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
print('\nCreate Report App Run Start, ', current_time)
# get the Cisco DNA Center Auth token
dnac_auth = get_dnac_jwt_token(DNAC_AUTH)
# find out the report view group id
report_view_groups = get_report_view_groups(dnac_auth)
for view in report_view_groups:
if view['category'] == REPORT_CATEGORY:
view_group_id = view['viewGroupId']
print('\nReport Category:', REPORT_CATEGORY)
print('Report View Group Id is:', view_group_id)
# find out the report view id's
report_view_ids = get_report_view_ids(view_group_id, dnac_auth)
report_views = report_view_ids['views']
for view in report_views:
if view['viewName'] == VIEW_NAME:
report_view_id = view['viewId']
print('Report View Name:', VIEW_NAME)
print('Report View Id is:', report_view_id)
# get the webhookId for the destination to send the report to
webhook_info = get_destination_by_name(WEBHOOK_NAME, dnac_auth)
webhook_id = webhook_info['instanceId']
print('Webhook Name:', WEBHOOK_NAME)
print('Webhook Id:', webhook_id, '\n')
# get the detailed report views
report_detail_view = get_detailed_report_views(report_view_id, view_group_id, dnac_auth)
print('\nClient Report Detail \n')
pprint(report_detail_view)
# create the report request payload
report_request = {
'name': REPORT_NAME,
'description': '',
'dataCategory': REPORT_CATEGORY,
'viewGroupId': view_group_id,
'viewGroupVersion': '2.0.0',
'schedule': {
'type': 'SCHEDULE_NOW'
},
'deliveries': [
{
'type': 'DOWNLOAD',
"default": True
},
{
'type': 'WEBHOOK',
'webhookId': webhook_id,
'default': False
}
],
'view': {
'name': VIEW_NAME,
'viewId': report_view_id,
'description': 'Client Report',
'fieldGroups': [
{
'fieldGroupName': 'client_details',
'fieldGroupDisplayName': 'Client Data',
'fields': [
{
'name': 'hostName',
'displayName': 'Host Name'
},
{
'name': 'username',
'displayName': 'User ID'
},
{
'name': 'macAddress',
'displayName': 'MAC Address'
},
{
'name': 'ipv4',
'displayName': 'IPv4 Address'
},
{
'name': 'ipv6',
'displayName': 'IPv6 Address'
},
{
'name': 'deviceType',
'displayName': 'Device Type'
},
{
'name': 'connectionStatus',
'displayName': 'Current Status'
},
{
'name': 'averageHealthScore_min',
'displayName': 'Min Health Score'
},
{
'name': 'averageHealthScore_max',
'displayName': 'Max Health Score'
},
{
'name': 'averageHealthScore_median',
'displayName': 'Median Health Score'
},
{
'name': 'usage_sum',
'displayName': 'Usage (MB)'
},
{
'name': 'connectedDeviceName',
'displayName': 'Connected Device Name'
},
{
'name': 'frequency',
'displayName': 'Band'
},
{
'name': 'rssi_median',
'displayName': 'RSSI (dBm)'
},
{
'name': 'snr_median',
'displayName': 'SNR (dB)'
},
{
'name': 'site',
'displayName': 'Last Location'
},
{
'name': 'lastUpdated',
'displayName': 'Last Seen'
},
{
'name': 'apGroup',
'displayName': 'AP Group'
},
{
'name': 'ssid',
'displayName': 'SSID'
},
{
'name': 'vlan',
'displayName': 'VLAN ID'
},
{
'name': 'vnid',
'displayName': 'VNID'
},
{
'name': 'onboardingEventTime',
'displayName': 'Onboarding Time'
},
{
'name': 'assocDoneTimestamp',
'displayName': 'Association Time'
},
{
'name': 'authDoneTimestamp',
'displayName': 'Authentication Time'
},
{
'name': 'aaaServerIp',
'displayName': 'Authentication Server'
},
{
'name': 'dhcpDoneTimestamp',
'displayName': 'Last DHCP Request'
},
{
'name': 'maxDhcpDuration_max',
'displayName': 'DHCP Response Time (ms)'
},
{
'name': 'dhcpServerIp',
'displayName': 'DHCP Server'
},
{
'name': 'linkSpeed',
'displayName': 'Link Speed (Mbps)'
},
{
'name': 'txRate_min',
'displayName': 'Min Tx Rate (bps)'
},
{
'name': 'txRate_max',
'displayName': 'Max Tx Rate (bps)'
},
{
'name': 'txRate_avg',
'displayName': 'Average Tx Rate (bps)'
},
{
'name': 'rxRate_min',
'displayName': 'Min Rx Rate (bps)'
},
{
'name': 'rxRate_max',
'displayName': 'Max Rx Rate (bps)'
},
{
'name': 'rxRate_avg',
'displayName': 'Average Rx Rate (bps)'
},
{
'name': 'txBytes_sum',
'displayName': 'Tx (MB)'
},
{
'name': 'rxBytes_sum',
'displayName': 'Rx (MB)'
},
{
'name': 'dataRate_median',
'displayName': 'Data Rate (Mbps)'
},
{
'name': 'dot11Protocol',
'displayName': 'Client Protocol'
}
]
}
],
'filters': [
{
'name': 'Location',
'displayName': 'Location',
'type': 'MULTI_SELECT_TREE',
'value': []
},
{
'name': 'DeviceType',
'displayName': 'Device Type',
'type': 'SINGLE_SELECT_ARRAY',
'value': []
},
{
'name': 'SSID',
'displayName': 'SSID',
'type': 'MULTI_SELECT',
'value': []
},
{
'name': 'Band',
'displayName': 'Band',
'type': 'MULTI_SELECT',
'value': []
},
{
'name': 'TimeRange',
'type': 'TIME_RANGE',
'displayName': 'Time Range',
'value': {
'timeRangeOption': 'LAST_24_HOURS',
'startDateTime': 0,
'endDateTime': 0
}
}
],
'format': {
'name': 'JSON',
'formatType': 'JSON',
'default': False
}
}
}
report_status = create_report(report_request, dnac_auth)
if report_status.status_code == 200:
print('\nReport submitted')
else:
print('\nReport not submitted, ', report_status.text)
current_time = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
print('\nCreate Report App Run End, ', current_time)
if __name__ == '__main__':
main()