import time import splunklib.client as client from splunklib.results import JSONResultsReader from splunklib.binding import HTTPError def connectSplunk(): HOST = "10.218.7.194" PORT = 8089 USERNAME = "" # Configurar como variable de entorno PASSWORD = "" # Configurar como variable de entorno try: service = client.connect(host=HOST, port=PORT, username=USERNAME, password=PASSWORD) print(service.token) return service except Exception as e: print(f'An error occurred while connecting to Splunk: {e}') return None def searchOldClient(service): search = ('| rest splunk_server=local /services/deployment/server/clients ' '| eval last_seen = now() - lastPhoneHomeTime ' '| where last_seen > 86400 ' '| rename clientName as guid ' '| fields guid') try: service.parse(search, parse_only=True) except HTTPError as e: print(f"query '{search}' is invalid:\n\t{str(e)}") return job = service.jobs.create(search) while not job.is_done(): time.sleep(2) result_stream = job.results(output_mode='json') results_reader = JSONResultsReader(result_stream) guids = list() for result in results_reader: if isinstance(result, dict) and 'guid' in result: guids.append(result['guid']) return guids def remove_client(service, guid): print(f'Removing: {guid}') endpoint = f'/services/deployment/server/clients/{guid}' try: response = service.delete(endpoint) print(f'Status: {response.status}') except HTTPError as e: print(f'Failed to remove client {guid}: {str(e)}') if __name__ == "__main__": service = connectSplunk() if service: old_clients = searchOldClient(service) for guid in old_clients: remove_client(service, guid)