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!

New Case Study: How LSU’s Student-Powered SOCs and Splunk Are Shaping the Future of ...

Louisiana State University (LSU) is shaping the next generation of cybersecurity professionals through its ...

Splunk and Fraud

Join us on November 13 at 11 am PT / 2 pm ET!Join us for an insightful webinar where we delve into the ...

Build Your First SPL2 App!

Watch the recording now!.Do you want to SPL™, too? SPL2, Splunk's next-generation data search and preparation ...