Advertisement
Guest User

Untitled

a guest
Nov 14th, 2018
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.76 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """DNAC Center North-Bound API Mission - edit this file
  3.  
  4. This is your starting point for the DNAC Center North-Bound API Mission.
  5. Edit this file to
  6. - retrieve network devices and modules from DNA Center
  7. - put them into a Python JSON object
  8. - write a JavaScript representation into a .js file which is formatted
  9. to be use with the NeXt UI Toolkit for visualization
  10.  
  11. There are a few places to edit (search for MISSION comments)
  12. 1 Provide the HTTP method type to retrieve information
  13. 2 Complete the URL to retrieve network devices
  14. 3 Complete the URL to retrieve device modules
  15. 4 Complete the URL to retrieve a count of modules
  16.  
  17. Script Dependencies:
  18. requests
  19.  
  20. Depencency Installation:
  21. $ pip install requests
  22.  
  23. Copyright (c) 2018, Cisco Systems, Inc. All rights reserved.
  24.  
  25. Permission is hereby granted, free of charge, to any person obtaining a copy
  26. of this software and associated documentation files (the "Software"), to deal
  27. in the Software without restriction, including without limitation the rights
  28. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  29. copies of the Software, and to permit persons to whom the Software is
  30. furnished to do so, subject to the following conditions:
  31.  
  32. The above copyright notice and this permission notice shall be included in all
  33. copies or substantial portions of the Software.
  34.  
  35. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  36. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  39. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  41. SOFTWARE.
  42. """
  43.  
  44. import ciscosparkapi
  45. import json
  46. import os
  47. import requests
  48. # Disable Certificate warning
  49. try:
  50. requests.packages.urllib3.disable_warnings()
  51. except:
  52. pass
  53. from requests.auth import HTTPBasicAuth
  54. import sys
  55.  
  56. # Get the absolute path for the directory where this file is located "here"
  57. here = os.path.abspath(os.path.dirname(__file__))
  58.  
  59. # Get the absolute path for the project / repository root
  60. project_root = os.path.abspath(os.path.join(here, '../..'))
  61.  
  62. # Extend the system path to include the project root and import the env files
  63. sys.path.insert(0, project_root)
  64. import env_lab # noqa
  65. import env_user # noqa
  66.  
  67.  
  68. # Create a Cisco Spark object
  69. spark = ciscosparkapi.CiscoSparkAPI(access_token=env_user.SPARK_ACCESS_TOKEN)
  70.  
  71.  
  72. # Details for DNA Center Platform API calls
  73. dnac_host = env_lab.DNA_CENTER['host']
  74. dnac_user = env_lab.DNA_CENTER['username']
  75. dnac_pass = env_lab.DNA_CENTER['password']
  76. dnac_headers = {'content-type': 'application/json'}
  77.  
  78. # Details for the NEXT UI File
  79. next_data_file = 'next-data-mission.js'
  80. next_data_file_header = '/*DO NOT EDIT - NeXt Topology file generated from DNA Center Device and Module Inventory*/\n\nvar topologyData = \n'
  81. next_data_file_footer = '\n/*DO NOT EDIT - EOF*/\n'
  82. next_data = {}
  83. next_data['nodes'] = []
  84. next_data['links'] = []
  85. next_icon = {'Switches and Hubs': 'switch',
  86. 'Routers': 'router',
  87. 'Wireless Controller': 'wlc',
  88. 'Unified AP': 'accesspoint'}
  89.  
  90.  
  91. def dnac_open_session(dnac_session,
  92. dnac_host,
  93. dnac_headers,
  94. dnac_username,
  95. dnac_password):
  96. """DNA Center login and adding cookie to session"""
  97. print('DNAC Login to ' + dnac_host + ' as ' + dnac_username + ' ...')
  98. dnac_auth_api = 'https://%s/api/system/v1/auth/login' % dnac_host
  99. r = dnac_session.get(dnac_auth_api,
  100. verify=False,
  101. headers=dnac_headers,
  102. auth=HTTPBasicAuth(dnac_username, dnac_password))
  103. r.raise_for_status()
  104. # print('DNAC Login: Response Headers: ' + str(r.headers))
  105. # print('DNAC Login: Response Body: ' + r.text)
  106.  
  107. session_token_val = ((r.headers['Set-Cookie']).split('=')[1]).split(';')[0]
  108. # session_token_val = r.json()["Token"]
  109. cookies = {'X-JWT-ACCESS-TOKEN': session_token_val}
  110. dnac_session.cookies.update(cookies)
  111. print('DNAC Login: Session Cookie: ' + str(cookies))
  112. return r
  113.  
  114.  
  115. # MISSION TODO 1: What type of HTTP method is used to retrieve information
  116. # from DNA Center Platform?
  117. def dnac_get_device_count(dnac_session, dnac_host, dnac_headers):
  118. """DNAC Network Device Count"""
  119. tmp_url = 'https://%s/api/v1/network-device/count' % dnac_host
  120. r = dnac_session.get(tmp_url, verify=False, headers=dnac_headers)
  121. r.raise_for_status()
  122. # print('DNAC Response Body: ' + r.text)
  123. return r.json()['response']
  124. # END MISSION SECTION
  125.  
  126.  
  127. # MISSION TODO 2: Complete the URL to retrieve the Network Devices
  128. def dnac_get_devices(dnac_session, dnac_host, dnac_headers):
  129. """DNAC Network Devices"""
  130. tmp_url = 'https://%s/api/v1/network-device' % dnac_host
  131. r = dnac_session.get(tmp_url, verify=False, headers=dnac_headers)
  132. r.raise_for_status()
  133. # print('DNAC Response Body: ' + r.text)
  134. return r.json()['response']
  135. # END MISSION SECTION
  136.  
  137.  
  138. def dnac_get_host_count(dnac_session, dnac_host, dnac_headers):
  139. """DNAC Host Count"""
  140. tmp_url = 'https://%s/api/v1/host/count' % dnac_host
  141. r = dnac_session.get(tmp_url, verify=False, headers=dnac_headers)
  142. r.raise_for_status()
  143. # print('DNAC Response Body: ' + r.text)
  144. return r.json()['response']
  145.  
  146.  
  147. # MISSION TODO 3: Complete the URL to retrieve the Modules about a device
  148. def dnac_get_modules(dnac_session, dnac_host, dnac_headers, device_id):
  149. """DNAC Modules of a Network Device"""
  150. tmp_url = 'https://%s/api/v1/' % dnac_host
  151. tmp_url = tmp_url + 'network-device/module?deviceId=%s' % device_id
  152.  
  153. r = dnac_session.get(tmp_url,
  154. verify=False,
  155. headers=dnac_headers
  156. )
  157. r.raise_for_status()
  158. # print('DNAC Response Body: ' + r.text)
  159. return r.json()['response']
  160. # END MISSION SECTION
  161.  
  162.  
  163. # MISSION TODO 4: Complete the URL to retrieve the number (or count) of
  164. # modules for a device
  165. def dnac_get_module_count(dnac_session, dnac_host, dnac_headers, device_id):
  166. """DNAC Module Count of a Network Device"""
  167. tmp_url = 'https://%s/api/v1/network-device/module/count' % dnac_host
  168. tmp_params = {'deviceId': device_id}
  169.  
  170. r = dnac_session.get(tmp_url,
  171. verify=False,
  172. headers=dnac_headers,
  173. params=tmp_params)
  174. r.raise_for_status()
  175. # print('DNAC Response Body: ' + r.text)
  176. return r.json()['response']
  177. # END MISSION SECTION
  178.  
  179.  
  180. with requests.Session() as dnac_session:
  181. r = dnac_open_session(dnac_session,
  182. dnac_host,
  183. dnac_headers,
  184. dnac_user,
  185. dnac_pass)
  186.  
  187. # Getting DNAC Device Count and Host Count verbose after login
  188. c = dnac_get_device_count(dnac_session, dnac_host, dnac_headers)
  189. print('DNAC Network Device Count: ' + str(c))
  190. c = dnac_get_host_count(dnac_session, dnac_host, dnac_headers)
  191. print('DNAC Host Count: ' + str(c))
  192.  
  193. # Put DNAC Network devices with modules into a JSON object
  194. devices = dnac_get_devices(dnac_session, dnac_host, dnac_headers)
  195. i = 0
  196. for d in devices:
  197. c = dnac_get_module_count(dnac_session,
  198. dnac_host,
  199. dnac_headers,
  200. d['id'])
  201. if c > 1:
  202. print('Device ' + d['id'] + ' with NeXt ID ' +
  203. str(i) + ' has ' + str(c) + ' modules')
  204. next_data['nodes'].append({'id ': i,
  205. 'x': (i*20),
  206. 'y': 80,
  207. 'name': d['hostname'],
  208. 'platform': d['platformId'],
  209. 'serial': d['serialNumber'],
  210. 'icon': next_icon[d['family']]})
  211. di = i
  212. i += 1
  213. modules = dnac_get_modules(dnac_session,
  214. dnac_host,
  215. dnac_headers,
  216. d['id'])
  217. for m in modules:
  218. next_data['nodes'].append({'id ': i,
  219. 'x': (i*20),
  220. 'y': 20*(i-di+1),
  221. 'name': m['description'],
  222. 'serial': d['serialNumber'],
  223. 'icon': 'server'})
  224. next_data['links'].append({'source': di, 'target': i})
  225. i += 1
  226.  
  227. # printing JSON representation to stdout
  228. print(json.dumps(next_data, indent=4, sort_keys=True))
  229.  
  230. # writing JavaScript representation into NeXt data file
  231. with open(next_data_file, 'w', encoding="utf-8") as outfile:
  232. print('Writing NeXt UI Topology Data File')
  233. outfile.write(next_data_file_header)
  234. outfile.write(json.dumps(next_data, indent=4, sort_keys=True))
  235. outfile.write(next_data_file_footer)
  236.  
  237. message = spark.messages.create(env_user.SPARK_ROOM_ID,
  238. files=[next_data_file],
  239. text='MISSION: DNA Center - I have completed the mission!')
  240. print(message)
  241.  
  242. print('\n\n')
  243. print('Network Devices and Modules from DNA Center have been written to ' +
  244. next_data_file)
  245. print('Open next-topology.html in Chrome Browser, so see the result')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement