Setting up search queries in Python for Splunk access. However, during my runs I ran into a IndexError: tuple index out of range
. I found in my code multiple {} and trying to use .format to apply variables earliest and latest was causing said error.
I've tried switching to .format_map but it causes more error unless I did something wrong. (Which could be)
I am not able to change the string that is in the code. So I am trying to find ways to append time variables to the string for use.
Here are the variable calls:
import _datetime_param
_earliest = _datetime_param.earliest()
_latest = _datetime_param.latest()
Formatting Works:
def eop():
search_query = (
'index="eop" sourcetype="eop:trace" Status="Quarantined" earliest={} latest={} | '
'convert timeformat="%Y-%m-%d %I:%M:%S" ctime(_time) as Date | '
'table Date src_ip src_user subject recipient | sort Date'
).format(_earliest, _latest)
search_query.strip()
if not (search_query.startswith('search') or search_query.startswith('|')):
search_query = 'search ' + search_query
return search_query
Formatting Runs Into Error:
def okta():
search_query = (
'index="okta" user!="CityADSync" action="failure" earliest={} latest={} | '
'convert timeformat="%Y-%m-%d %I:%M:%S" ctime(_time) AS Date | dedup actors{}.ipAddress | '
'rename actors{}.ipAddress AS IPAddress | rename actors{}.id AS Device | rename targets{}.id AS TargetID | '
'rename targets{}.displayName AS TargetName| rename targets{}.login AS TargetLogin | '
'table Date Device IPAddress TargetID TargetName TargetLogin | sort Date'
).format(_earliest, _latest)
search_query.strip()
if not (search_query.startswith('search') or search_query.startswith('|')):
search_query = 'search ' + search_query
return search_query
In the def okata():
I can't change the search_query
as its set to run that way in Splunk. So I am looking for a way to cleanly handle both ways while not running into error. Put bluntly is there a way in Python to ignore {} you don't want to use? If it is .format_map
, is there a clean way to do so that I am missing?
Thanks in advance!