Skip to content

Instantly share code, notes, and snippets.

@ww9rivers
Created August 20, 2023 19:20
Show Gist options
  • Save ww9rivers/4bfc59780e5263aabc738a8f1166e740 to your computer and use it in GitHub Desktop.
Save ww9rivers/4bfc59780e5263aabc738a8f1166e740 to your computer and use it in GitHub Desktop.
Simple Python3 script to start a Splunk search (the search actually fetches the results of a scheduled search that outputs to search-results.csv)
#!/usr/bin/env python3
import os
import requests
# Set up the session with our adapter
SEARCH_ENDPOINT = "https://"+os.environ['SPLUNK_HOST']+":8089/services/search/jobs"
headers = {
'Authorization': 'Bearer '+os.environ['SPLUNK_TOKEN'],
"Accept": "application/json"
}
params = {
"search": "inputcsv search-results.csv",
"output_mode": "json"
}
response = requests.post(SEARCH_ENDPOINT, data=params, headers=headers, verify=True)
print(response.text)
@ww9rivers
Copy link
Author

ww9rivers commented Aug 20, 2023

The script requires 2 environment variables to work:

  • SPLUNK_HOST -- DNS name of the host where the search is to be run. for example __instance__.splunkcloud.com.
  • SPLUNK_TOKEN -- A token for authentication configured on the host for the user that runs the search.

This script does not complete the job -- it merely starts a job running and then returns the search job Id in the response.text.

Some more details (with line numbers):

  • 6: SEARCH_ENDPOINT -- the REST API endpoint in Splunk to start a search job.
  • 7: headers -- the HTTP request headers:
    • Authentication: user authentication data -- token authentication is to be used.
    • Accept: what format of output we accept for this REST API call.
  • 11: params -- the data to send to the REST API:
    • search -- the Splunk SPL command to run;
    • output_mode -- the format we want the search output to be.

Again, this script just starts the search job, then prints out the search job id if successful. No error handling is done.

When the script works, it is expected to return something like this: {"sid":"1692372424.340196"}. That is a search job id that may be used later to poll for the status of the job and fetch the results.

When there is an error, it probably will print out an error message. For example, when the token authentication does not work, the output is:
{"messages":[{"type":"WARN","text":"call not properly authenticated"}]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment