Python script to delete asset by providing the hostname

Python script to delete asset by providing the hostname

To use this python script, place the API credentials json file and this script in the same folder and run this script from that folder.

Inputs to this script :
  1. fileName of the JSON Credentials file
  2. HostName of asset to be deleted
External modules used (command to install):
  1. requests (pip install requests)
  2. jwt (pip install jwt)
Note : if you encounter this error "JWT has no attribute encode", please run below commands :
  1. pip uninstall jwt pyJWT
  2. pip install pyJWT

Script : 

  1. import requests
    import json
    import time
    import datetime as dt
    import jwt
    import os

    heading = """

                ██    ██ ██████  ████████ ██    ██  ██████ ███████ 
                ██    ██ ██  ██     ██     ██  ██  ██      ██      
                ██    ██ ██████     ██      ████   ██      ███████ 
                ██    ██ ██         ██       ██    ██           ██ 
                 ██████  ██         ██       ██     ██████ ███████ 

    """

    def read_file(path):
        try:
            with open(path, 'r') as f:
                return json.loads(f.read())
        except FileNotFoundError:
            print(path, "Not found")
            exit(-1)
        except:
            print('Error: something went wrong')
            exit(-1)



    # main

    print(heading, end='\n\n\n')

    filePath = input('Enter the fileName of json file that have API keys (store json file in current folder)\n')
    data = read_file(path=os.getcwd() + "\\" + filePath)

    seconds_to_expiry = 3600
    exp = time.time() + seconds_to_expiry
    expiry = dt.datetime.fromtimestamp(exp).strftime('%Y-%m-%d %H:%M')
    domain = data['domain']
    customerId = data['customerId']
    key = data['key']
    secret = data['secret']
    domainSuffix = data['domainSuffix']
    token = jwt.encode({'iss':key, 'exp':exp}, secret, algorithm='HS256')
    auth = f'Bearer {token}'



    creds = {'domain':domain,'customerId':customerId}
    creds['Expiration'] = expiry
    creds['Authorization'] = auth

    hostName = input("Enter the Host Name of asset to be deleted \n")
    filters = "{%22hostName%22%3A{%22equals%22%3A%22" + hostName +"%22}}"

    print("\nAuth Token is ready")
    print("\nCalling API...")

    # Format the URL
    assetInfoURL = f'https://{domain}{domainSuffix}/public/api/customers/{customerId}/assets?filters={filters}'
    response = requests.get(assetInfoURL, headers=creds)

    if(response.status_code == 200):
        data = response.json()
        assetId = data['items'][0]['id']
        print("\nSuccess!!!")
        print(f"\nAssetId Received: {assetId}")

        print("\nDeleting Asset...")
        # Format the URL
        assetDeletionURL = f'https://{domain}.uptycs.io/public/api/customers/{customerId}/assets/{assetId}'
        response = requests.delete(assetDeletionURL, headers=creds)
        
        if(response.status_code == 200):
            print("\nAsset Deletion Completed!!!")
        else:
            print("\nError while deleting asset")
            print(response.json())
    else:
        print("\nError!!!")
        print(response.json())


    • Related Articles

    • Delete duplicate assets using the API

      Duplicate asset (hostname) on Uptycs platform could be a result of particular asset being in rotation or being used a a loaner laptop in which case, uuid of the asset remains the same and the asset is recorded under different hostnames. Following ...
    • Delete assets offline since a particular date using the API

      This script / procedure outlines the process to delete assets which have been offline before a particular date. Prerequisite tools iusql urestapi Procedure Download api key from Uptycs UI Download attached script, delete_offline_assets_since.sh     ...
    • Python helper module for Uptycs API

      The attached helper module (uptapi.py) and demo program (uptdemo.py) show how to access Uptycs API from Python 3. 
    • Uptycs Alert Triggers API Call

      This python module can be run to trigger Uptycs API calls from Uptycs alerts.  Example: An alert is configured to fire when asset location is not in USA (possible GDPR issue). This python can then be run to automatically make an API call to disable ...
    • Uptycs APIs to get the list of vulnerabilities for a Host, CVE or Package

      This document outlines the APIs required to retrieve the vulnerability data for a given host / CVE / package. Sample python scripts attached to this document (vulnerabilities_api_sample.zip): The attached package contains a list of sample python ...