Created
September 5, 2017 06:04
-
-
Save sduff/aca550a8df636fdc07326225de380a91 to your computer and use it in GitHub Desktop.
Splunk search via Python, using Requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time # need for sleep | |
from xml.dom import minidom | |
import json, pprint | |
import requests | |
from requests.packages.urllib3.exceptions import InsecureRequestWarning | |
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) | |
base_url = 'https://localhost:8089' | |
username = 'admin' | |
password = 'changeme' | |
search_query = "search=search index=*" | |
r = requests.get(base_url+"/servicesNS/admin/search/auth/login", | |
data={'username':username,'password':password}, verify=False) | |
session_key = minidom.parseString(r.text).getElementsByTagName('sessionKey')[0].firstChild.nodeValue | |
print ("Session Key:", session_key) | |
r = requests.post(base_url + '/services/search/jobs/', data=search_query, | |
headers = { 'Authorization': ('Splunk %s' %session_key)}, | |
verify = False) | |
sid = minidom.parseString(r.text).getElementsByTagName('sid')[0].firstChild.nodeValue | |
print ("Search ID", sid) | |
done = False | |
while not done: | |
r = requests.get(base_url + '/services/search/jobs/' + sid, | |
headers = { 'Authorization': ('Splunk %s' %session_key)}, | |
verify = False) | |
response = minidom.parseString(r.text) | |
for node in response.getElementsByTagName("s:key"): | |
if node.hasAttribute("name") and node.getAttribute("name") == "dispatchState": | |
dispatchState = node.firstChild.nodeValue | |
print ("Search Status: ", dispatchState) | |
if dispatchState == "DONE": | |
done = True | |
else: | |
time.sleep(1) | |
r = requests.get(base_url + '/services/search/jobs/' + sid + '/results/', | |
headers = { 'Authorization': ('Splunk %s' %session_key)}, | |
data={'output_mode': 'json'}, | |
verify = False) | |
pprint.pprint(json.loads(r.text)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code . If search query has expressions like eval raw_dt_tm_stamp=strftime(_time,"%Y%m%d %H:%M:%S.%6N") or eval var1=replace(mvindex(temp,6),""","") execution failing with error Unparsable URI-encoded request data. Can you please let me know how to handle these errors