Splunk Dev

Why is Splunk App self._metadata.searchinfo.session_key and Service is none?

Lugia
Engager

Hello,

I have created a splunk app, very similar to the weather example here on github

My app needs to be authenticated in order to access the 'service.storage_passwords' , however when running the command on my admin Splunk account

 

|test_command

 

'None' is being printed in my search.log file for the authenticated object.

 

This is my Python code -

 

#Various imports
logger = logging.getLogger("MyCommand")
logger.setLevel(logging.DEBUG)

@Configuration()
class MyCommand(GeneratingCommand):
    ip = Option(require=True)

    def generate(self):
        try:
            logger.debug("Starting MyCommand run")

            service = self.service # THIS IS NONE
            sesh_key = self._metadata.searchinfo.session_key) # THIS IS NONE
            logger.debug(service) #None
            logger.debug(sesh_key) #None

# Dispatch your custom search command
dispatch(MyCommand, sys.argv, sys.stdin, sys.stdout, __name__)

 

 

and my commands.conf (unsure if these options are correct)

 

[test_command]
type = python
filename = test_command.py
supports_getinfo = true
supports_rawargs = true
passauth = true
enableheader = true

 

  

I assume I am missing something fairly obvious regarding how to pass authentication into my app when a command is ran, however I cannot determine the issue.

 

Appreciate any help.

Labels (4)
Tags (1)
0 Karma
1 Solution

VatsalJagani
SplunkTrust
SplunkTrust

@Lugia - When things don't work start with simple:

 

import os,sys
import logging

# Library-loading boilerplate
APP_NAME = 'my_app'
splunkhome = os.environ['SPLUNK_HOME']
apphome = os.path.join(splunkhome, 'etc', 'apps', APP_NAME)
sys.path.append(os.path.join(apphome, 'vendor'))

from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option, validators


@Configuration()
class MyCommand(GeneratingCommand):
    ip = Option(require=True)

    def generate(self):
        yield {"msg": f"Your session key is {self.search_results_info.auth_token}"}

# Dispatch your custom search command
dispatch(MyCommand, sys.argv, sys.stdin, sys.stdout, __name__)

 

Moreover while using splunklib I would not recommend doing "sys.stdin.readline()" as it would create a problem.

Do not override __ini__.

 

I hope this helps!!!

View solution in original post

0 Karma

VatsalJagani
SplunkTrust
SplunkTrust

@Lugia - Use "self.search_results_info.auth_token" instead of what you have used.

if not self.search_results_info or not self.search_results_info.auth_token:
    logger.error("Unable to get session key in the custom command.")
        raise Exception("Unable to get session key.")
    return self.search_results_info.auth_token

 

I hope this helps!!!

0 Karma

Lugia
Engager

Appreciate the response! 

Using that code, I am getting

'AttributeError: 'ObjectView' object has no attribute 'auth_token''

 

Incase these steps are wrong: This is after transferring the apps files into the /etc/apps folder, Using the splunk refresh button, then using the 'search' tab within my app to run the command. 

 

This is my current commands.conf - Unsure if this is what is required?

 

 

[test_command]

type = python

filename = test_command.py

supports_getinfo = true

supports_rawargs = true

passauth = true

enableheader = true

requires_srinfo = true

python.version = python3

 

 

Tags (3)
0 Karma

VatsalJagani
SplunkTrust
SplunkTrust

@Lugia - Kindly show your code under "tzip.py
". You can hide code which you think is non-disclosive for you.

 

0 Karma

Lugia
Engager

No problem, this is the code of that .py (renamed it to be more generic for this)

All the logger.debug messages print none for search info / session key stuff

 

"""
Custom Splunk Command

"""

import os,sys
import logging
import splunk.Intersplunk
from utils import Utils

# Library-loading boilerplate
APP_NAME = 'my_app'
splunkhome = os.environ['SPLUNK_HOME']
apphome = os.path.join(splunkhome, 'etc', 'apps', APP_NAME)
sys.path.append(os.path.join(apphome, 'vendor'))

import splunklib.client as client
from splunklib.client import Service
from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option, validators


@Configuration()
class MyCommand(GeneratingCommand):
    ip = Option(require=True)

    def generate(self):
        logger = self.utils.setup_logger()
        logger.debug("Starting command search")
        try:

            logger.debug(self.service) 
            logger.debug(self._metadata.searchinfo.session_key)
            #logger.debug(self._metadata.searchinfo.auth_token)
            logger.debug(sys.stdin.readline().strip())
            logger.debug(self.search_results_info.auth_token)
            logger.debug(f"Splunk version: {service.info.version}") #This errors

            # Extract IP addresses from the command's argument
            logger.debug("ip pased into search " + self.ip)

        except Exception as e:
            logger.error("Error:", e)
    def __init__(self):
        super(MyCommand, self).__init__()

        # Initialize Utils class with the session key
        session_key = sys.stdin.readline().strip()
        self.utils = Utils(session_key)


# Dispatch your custom search command
dispatch(MyCommand, sys.argv, sys.stdin, sys.stdout, __name__)

 

0 Karma

VatsalJagani
SplunkTrust
SplunkTrust

@Lugia - When things don't work start with simple:

 

import os,sys
import logging

# Library-loading boilerplate
APP_NAME = 'my_app'
splunkhome = os.environ['SPLUNK_HOME']
apphome = os.path.join(splunkhome, 'etc', 'apps', APP_NAME)
sys.path.append(os.path.join(apphome, 'vendor'))

from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option, validators


@Configuration()
class MyCommand(GeneratingCommand):
    ip = Option(require=True)

    def generate(self):
        yield {"msg": f"Your session key is {self.search_results_info.auth_token}"}

# Dispatch your custom search command
dispatch(MyCommand, sys.argv, sys.stdin, sys.stdout, __name__)

 

Moreover while using splunklib I would not recommend doing "sys.stdin.readline()" as it would create a problem.

Do not override __ini__.

 

I hope this helps!!!

0 Karma
Get Updates on the Splunk Community!

Introduction to Splunk Observability Cloud - Building a Resilient Hybrid Cloud

Introduction to Splunk Observability Cloud - Building a Resilient Hybrid Cloud  In today’s fast-paced digital ...

Observability protocols to know about

Observability protocols define the specifications or formats for collecting, encoding, transporting, and ...

Take Your Breath Away with Splunk Risk-Based Alerting (RBA)

WATCH NOW!The Splunk Guide to Risk-Based Alerting is here to empower your SOC like never before. Join Haylee ...