I am trying to get the result of a search from Splunk, but when I try to get the session key, I am getting the following error.
Traceback (most recent call last): File "splunkenter.py", line 18, in sessionkey = minidom.parseString(servercontent).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue IndexError: list index out of range
Can anybody tell me where is the problem lying? I am very new to API's.
Assuming you are writing a scripted input or modular input, you can read the session key like this:
config_str = sys.stdin.read()
doc = xml.dom.minidom.parseString(config_str)
root = doc.documentElement
sessionkey = root.getElementsByTagName("session_key")[0].firstChild.data
config["session_key"] = sessionkey
The error you are seeing is that there doesn't exist an array for one of the elements. So either getElementsByTagName('sessionKey')[0]
has no data or childNodes[0]
has no data. Those would be the two arrays that would cause that error. Try splitting the call apart into different variables and isolate which one is not returning correctly.
I am not reading anything from the standard input. I just want to obtain the session key for the on going session.
config_str = sys.stdin.read() -> This prompts user to input something.
Whereas i don't want to input anything. I am just trying to retrieve the session id for the session in order to connect to the splunk.
This is the code that i am using
import urllib
import httplib2
import time
import re
from time import localtime,strftime
from xml.dom import minidom
import json
baseurl = 'https://localhost:8089'
username = ''
password = ''
myhttp = httplib2.Http()
servercontent = myhttp.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
print "====>sessionkey: %s <====" % sessionkey
Ok, so now you have another array. myhttp.request(baseurl + '/services/auth/login', 'POST',
now might not have a
headers={}, body=urllib.urlencode({'username': username, 'password': password}))1
index in it. Try using exceptions to figure it out.
try:
servercontent = myhttp.request(baseurl + '/services/auth/login', 'POST',
headers={}, body=urllib.urlencode({'username': username, 'password': password}))[1]
except:
print "error in retrieving login."
try:
sessionkey = minidom.parseString(servercontent).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue
print "====>sessionkey: %s <====" % sessionkey
except:
print "error in retrieving sessionkey"