Script working
This commit is contained in:
65
removeOldClientsDS.py
Normal file
65
removeOldClientsDS.py
Normal file
@@ -0,0 +1,65 @@
|
||||
import time
|
||||
import splunklib.client as client
|
||||
import splunklib.results as results
|
||||
import splunklib.binding as binding
|
||||
from splunklib.results import JSONResultsReader
|
||||
from splunklib.binding import HTTPError
|
||||
|
||||
def connectSplunk():
|
||||
HOST = "10.218.7.194"
|
||||
PORT = 8089
|
||||
USERNAME = "" # Configurar variable de entorno
|
||||
PASSWORD = "" # Configurar 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)
|
||||
# Wait for the job to complete
|
||||
while not job.is_done():
|
||||
time.sleep(2)
|
||||
|
||||
# Retrieve and display the results
|
||||
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: # Check if the result is a dictionary (a valid search 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)
|
||||
Reference in New Issue
Block a user