Alerting

Run Python 3.x script in alerts

yashjain12yj
New Member

I want to execute python 3 scripts when an alert is triggered.
Since Splunk default comes with python 2.x, but is there any way to convert it to python 3.x?

0 Karma

sdchakraborty
Contributor

Can you try the below setup and see whether it works? The idea is to wrap your script within another python script so that when your script will run it will run using system python not splunk python. I have just given example of two different environments. You can modify the code related to platforms accordingly.

import os 
import subprocess
import sys

import logging
wrapped_script="<your actual script name>"


_SPLUNK_HOME=os.environ['SPLUNK_HOME']
_SPLUNK_PYTHON_PATH = os.environ['PYTHONPATH']
os.environ['LD_LIBRARY_PATH']='' #hack to stop splunk libries loading instead of system

if sys.platform == "win32":
    logfilename = 'searchcommand2_app.log'
    _APP_BIN_HOME=_SPLUNK_HOME + "<your actual script path>"
    _NEW_PYTHON_PATH = "<your python 3.x path>"
    os.environ['PYTHONPATH'] = _NEW_PYTHON_PATH
    my_process = _APP_BIN_HOME + "\\" + wrapped_script
elif sys.platform == "darwin" or sys.platform == "linux" or sys.platform == "linux2":
    logfilename = 'searchcommand2_app.log'
    _APP_BIN_HOME = _SPLUNK_HOME + "<your actual script path>"
    _NEW_PYTHON_PATH = "<your python 3.x path>"
    os.environ['PYTHONPATH'] = _NEW_PYTHON_PATH
    my_process = _APP_BIN_HOME + "/" + wrapped_script




logging.basicConfig(filename=logfilename, level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
mylogger = logging.getLogger("ourlogger")
mylogger.debug("wrapper: sys.argv=%s" % sys.argv) 



argstr=''
for thing in sys.argv:
    argstr=argstr + " " + thing

p = subprocess.Popen([os.environ['PYTHONPATH'], my_process, _SPLUNK_PYTHON_PATH ] + sys.argv[1:] , stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
0 Karma
Get Updates on the Splunk Community!

Routing logs with Splunk OTel Collector for Kubernetes

The Splunk Distribution of the OpenTelemetry (OTel) Collector is a product that provides a way to ingest ...

Welcome to the Splunk Community!

(view in My Videos) We're so glad you're here! The Splunk Community is place to connect, learn, give back, and ...

Tech Talk | Elevating Digital Service Excellence: The Synergy of Splunk RUM & APM

Elevating Digital Service Excellence: The Synergy of Real User Monitoring and Application Performance ...