Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.75 KB | None | 0 0
  1. from datetime import datetime
  2. from datetime import timedelta
  3. import jwt
  4. import uuid
  5. import requests
  6. import json
  7.  
  8.  
  9.  
  10.  
  11. def get_access_token():
  12.  
  13. # Create Authentication token which is used to retrieve an access token for further API access.
  14. timeout = 1800 # 30 minutes from now
  15. now = datetime.utcnow()
  16. timeout_datetime = now + timedelta(seconds=timeout)
  17. epoch_time = int((now - datetime(1970, 1, 1)).total_seconds())
  18. epoch_timeout = int((timeout_datetime - datetime(1970, 1, 1)).total_seconds())
  19. jti_val = str(uuid.uuid4())
  20. claims = {
  21. 'exp': epoch_timeout,
  22. 'iat': epoch_time,
  23. 'iss': 'http://cylance.com',
  24. 'sub': tenant['Application ID'],
  25. 'tid': tenant['Tenant ID'],
  26. 'jti': jti_val
  27. }
  28. url = 'https://protectapi.cylance.com/auth/v2/token'
  29. encoded = jwt.encode(claims, tenant['Application Secret'], algorithm='HS256')
  30. payload = {'auth_token': encoded.decode('utf-8')}
  31. headers = {'Content-Type': 'application/json; charset=utf-8'}
  32. try:
  33. resp = requests.post(url, headers=headers, data=json.dumps(payload))
  34. return json.loads(resp.text)['access_token']
  35. except Exception as e:
  36. print('ERROR: Please Ensure Tenant Information is correct. Failed to retrieve access token:', e)
  37.  
  38.  
  39.  
  40. def get_all_devices():
  41. All = []
  42. header = {"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + get_access_token()}
  43. r = requests.get('https://protectapi' + tenant['Region Code'] + '.cylance.com/devices/v2?page_size=200', headers=header)
  44. jsonData = json.loads(r.text)
  45. for dev in jsonData['page_items']:
  46. All.append(dev)
  47. pages = jsonData['total_pages']
  48. if pages > 1:
  49. for x in range (2, pages + 1):
  50. r = requests.get('https://protectapi' + tenant['Region Code'] + '.cylance.com/devices/v2?page='+ str(x) + 'page_size=200', headers=header)
  51. jsonData = json.loads(r.text)
  52. for dev in jsonData['page_items']:
  53. All.append(dev)
  54. return All
  55. #
  56.  
  57. def get_all_packages():
  58. All = []
  59. access_token = get_access_token()
  60. headers = {'Accept': 'application/json', 'Authorization': 'Bearer ' + access_token}
  61. url = 'https://protectapi' + tenant['Region Code'] + '.cylance.com/packages/v2?page_size=200'
  62. try:
  63. resp = requests.get(url, headers=headers)
  64. except Exception as e:
  65. raise Exception('Failed to get packages: {}'.format(e))
  66. if resp.status_code >= 200 and resp.status_code < 300:
  67. try:
  68. if resp.text != '':
  69. data = json.loads(resp.text)
  70. for item in data['page_items']:
  71. All.append(item)
  72. pages = data['total_pages']
  73. if pages > 1:
  74. for x in range (2, pages + 1):
  75. url = 'https://protectapi' + tenant['Region Code'] + '.cylance.com/packages/v2?page='+ str(x) + 'page_size=200'
  76.  
  77. resp = requests.get(url, headers=headers)
  78. data = json.loads(resp.text)
  79. for item in data['page_items']:
  80. All.append(item)
  81. return All
  82. except Exception as e:
  83. raise Exception('Json error with the return data: {}'.format(e))
  84. else:
  85. raise Exception('Failed to get packages.')
  86.  
  87.  
  88. def show_data():
  89. devices = get_all_devices()
  90.  
  91. for dev in devices:
  92. print()
  93. print(dev['name'])
  94. print(dev['state'])
  95.  
  96. dev['id'] = dev['id'].replace('-', '')
  97. dev['id'] = dev['id'].upper()
  98. print(dev['id'])
  99.  
  100. packages = get_all_packages()
  101. for package in packages:
  102. print()
  103. print( package['packageDescriptor']['name'] )
  104. print( package['packageId'])
  105. try:
  106. print( package['downloadUrl'])
  107. except Exception:
  108. print('Missing download url')
  109.  
  110.  
  111.  
  112.  
  113. ##########################################################################################################
  114. ##########################################################################################################
  115. ##########################################################################################################
  116.  
  117. tenant = {
  118. 'Tenant ID' : '',
  119. 'Application ID' : '',
  120. 'Application Secret':'' ,
  121. 'Region Code' : ''
  122. }
  123.  
  124.  
  125. #this function will show all devices and their IDs, as well as each package and its download URL
  126.  
  127. #show_data()
  128.  
  129.  
  130. devices = [ 'myDeviceId' ]
  131.  
  132. packageDownloadURL = [ 'myDownloadURL' ]
  133.  
  134.  
  135. payload = {
  136. 'execution': {
  137. 'name': 'Package Execution',
  138. 'target': {
  139. 'devices': devices
  140. },
  141. 'destination': '',
  142. 'packageExecutions': [
  143. {
  144. 'arguments': [
  145. ''
  146. ],
  147. 'package':
  148. packageDownloadURL
  149. }
  150. ],
  151. 'keepResultsLocally':True
  152. }
  153. }
  154.  
  155.  
  156. access_token = get_access_token()
  157. url = 'https://protectapi.cylance.com/packages/v2/executions'
  158. headers = {'Accept': 'application/json', 'Authorization': 'Bearer ' + access_token}
  159. resp = requests.post(url, headers=headers, data=json.dumps(payload))
  160.  
  161. data = json.loads(resp.text)
  162. code = resp.status_code
  163.  
  164. print()
  165. print('Code: ' + str(code))
  166. print(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement