Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime
- from datetime import timedelta
- import jwt
- import uuid
- import requests
- import json
- def get_access_token():
- # Create Authentication token which is used to retrieve an access token for further API access.
- timeout = 1800 # 30 minutes from now
- now = datetime.utcnow()
- timeout_datetime = now + timedelta(seconds=timeout)
- epoch_time = int((now - datetime(1970, 1, 1)).total_seconds())
- epoch_timeout = int((timeout_datetime - datetime(1970, 1, 1)).total_seconds())
- jti_val = str(uuid.uuid4())
- claims = {
- 'exp': epoch_timeout,
- 'iat': epoch_time,
- 'iss': 'http://cylance.com',
- 'sub': tenant['Application ID'],
- 'tid': tenant['Tenant ID'],
- 'jti': jti_val
- }
- url = 'https://protectapi.cylance.com/auth/v2/token'
- encoded = jwt.encode(claims, tenant['Application Secret'], algorithm='HS256')
- payload = {'auth_token': encoded.decode('utf-8')}
- headers = {'Content-Type': 'application/json; charset=utf-8'}
- try:
- resp = requests.post(url, headers=headers, data=json.dumps(payload))
- return json.loads(resp.text)['access_token']
- except Exception as e:
- print('ERROR: Please Ensure Tenant Information is correct. Failed to retrieve access token:', e)
- def get_all_devices():
- All = []
- header = {"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + get_access_token()}
- r = requests.get('https://protectapi' + tenant['Region Code'] + '.cylance.com/devices/v2?page_size=200', headers=header)
- jsonData = json.loads(r.text)
- for dev in jsonData['page_items']:
- All.append(dev)
- pages = jsonData['total_pages']
- if pages > 1:
- for x in range (2, pages + 1):
- r = requests.get('https://protectapi' + tenant['Region Code'] + '.cylance.com/devices/v2?page='+ str(x) + 'page_size=200', headers=header)
- jsonData = json.loads(r.text)
- for dev in jsonData['page_items']:
- All.append(dev)
- return All
- #
- def get_all_packages():
- All = []
- access_token = get_access_token()
- headers = {'Accept': 'application/json', 'Authorization': 'Bearer ' + access_token}
- url = 'https://protectapi' + tenant['Region Code'] + '.cylance.com/packages/v2?page_size=200'
- try:
- resp = requests.get(url, headers=headers)
- except Exception as e:
- raise Exception('Failed to get packages: {}'.format(e))
- if resp.status_code >= 200 and resp.status_code < 300:
- try:
- if resp.text != '':
- data = json.loads(resp.text)
- for item in data['page_items']:
- All.append(item)
- pages = data['total_pages']
- if pages > 1:
- for x in range (2, pages + 1):
- url = 'https://protectapi' + tenant['Region Code'] + '.cylance.com/packages/v2?page='+ str(x) + 'page_size=200'
- resp = requests.get(url, headers=headers)
- data = json.loads(resp.text)
- for item in data['page_items']:
- All.append(item)
- return All
- except Exception as e:
- raise Exception('Json error with the return data: {}'.format(e))
- else:
- raise Exception('Failed to get packages.')
- def show_data():
- devices = get_all_devices()
- for dev in devices:
- print()
- print(dev['name'])
- print(dev['state'])
- dev['id'] = dev['id'].replace('-', '')
- dev['id'] = dev['id'].upper()
- print(dev['id'])
- packages = get_all_packages()
- for package in packages:
- print()
- print( package['packageDescriptor']['name'] )
- print( package['packageId'])
- try:
- print( package['downloadUrl'])
- except Exception:
- print('Missing download url')
- ##########################################################################################################
- ##########################################################################################################
- ##########################################################################################################
- tenant = {
- 'Tenant ID' : '',
- 'Application ID' : '',
- 'Application Secret':'' ,
- 'Region Code' : ''
- }
- #this function will show all devices and their IDs, as well as each package and its download URL
- #show_data()
- devices = [ 'myDeviceId' ]
- packageDownloadURL = [ 'myDownloadURL' ]
- payload = {
- 'execution': {
- 'name': 'Package Execution',
- 'target': {
- 'devices': devices
- },
- 'destination': '',
- 'packageExecutions': [
- {
- 'arguments': [
- ''
- ],
- 'package':
- packageDownloadURL
- }
- ],
- 'keepResultsLocally':True
- }
- }
- access_token = get_access_token()
- url = 'https://protectapi.cylance.com/packages/v2/executions'
- headers = {'Accept': 'application/json', 'Authorization': 'Bearer ' + access_token}
- resp = requests.post(url, headers=headers, data=json.dumps(payload))
- data = json.loads(resp.text)
- code = resp.status_code
- print()
- print('Code: ' + str(code))
- print(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement