Skip to content

Instantly share code, notes, and snippets.

@LeeSartorelli
Last active February 17, 2019 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeeSartorelli/d7af4646dd801f89611b86008e8a9d31 to your computer and use it in GitHub Desktop.
Save LeeSartorelli/d7af4646dd801f89611b86008e8a9d31 to your computer and use it in GitHub Desktop.
This function runs a Splunk search, and can be added to any python script that requires input from a Splunk search.
# function that accepts a Splunk URL and Splunk search query, and returns the search results
# requires Splunk credentials to be stored in a .netrc file in the user's home directory
# adapted from https://docs.splunk.com/Documentation/Splunk/7.2.4/RESTTUT/RESTsearches)
# Note this won't work for searches with over 50,000 results - https://www.splunk.com/blog/2013/09/15/exporting-large-results-sets-to-csv.html
import urllib, httplib2, netrc
from xml.dom import minidom
baseurl = 'https://localhost:8089'
searchQuery = 'ENTER SEARCH QUERY HERE'
def splunkSearch( baseurl, searchQuery ):
# retrieve credentials from netrc file in home directory
secrets = netrc.netrc()
username, account, password = secrets.authenticators('localhost')
# Authenticate with server.
# Disable SSL cert validation. Splunk certs are self-signed.
serverContent = httplib2.Http(disable_ssl_certificate_validation=True).request(baseurl + '/services/auth/login', 'POST', headers={}, body=urllib.urlencode({'username':username, 'password':password}))[1]
sessionKey = minidom.parseString(serverContent).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue
# Remove leading and trailing whitespace from the search
searchQuery = searchQuery.strip()
# If the query doesn't already start with the 'search' operator or another generating command (e.g. "| inputcsv"), then prepend "search " to it.
if not (searchQuery.startswith('search') or searchQuery.startswith("|")): searchQuery = 'search ' + searchQuery
# Run the search.
# Again, disable SSL cert validation.
searchJob = httplib2.Http(disable_ssl_certificate_validation=True).request(baseurl + '/services/search/jobs/export','POST',headers={'Authorization': 'Splunk %s' % sessionKey},body=urllib.urlencode({'search': searchQuery, 'output_mode': 'csv'}))[1]
return searchJob;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment