Skip to content

Instantly share code, notes, and snippets.

@marcusschiesser
Last active February 10, 2022 03:43
Show Gist options
  • Save marcusschiesser/6b333f834bd79d66c60c0af04b026453 to your computer and use it in GitHub Desktop.
Save marcusschiesser/6b333f834bd79d66c60c0af04b026453 to your computer and use it in GitHub Desktop.
Using username or token authentication in Splunk from Python
from utils import connect
service = connect(
app=os.getenv('SPLUNK_APP'),
host=os.getenv('SPLUNK_HOST'),
port=os.getenv('SPLUNK_PORT', 8089),
token=os.getenv('SPLUNK_TOKEN'),
username=os.getenv('SPLUNK_USERNAME'),
password=os.getenv('SPLUNK_PASSWORD')
)
import splunklib.client
def connect(**kwargs):
# remove `None` parameters (otherwise splunklib.client.connect will fail)
for key in ['username', 'password', 'token', 'host', 'port']:
if key in kwargs and kwargs[key] is None:
del kwargs[key]
# ensure parameters
for key in ['host', 'port']:
if key not in kwargs:
raise ValueError(
f"Can't connect to Splunk. Missing {key} parameter")
if 'username' in kwargs and 'password' not in kwargs:
raise ValueError(
f"Can't connect to Splunk {kwargs['host']}. Missing password for username authentication")
if 'username' not in kwargs and 'token' not in kwargs:
raise ValueError(
f"Can't connect to Splunk {kwargs['host']}. Either token or username must be set for authentication")
return splunklib.client.connect(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment