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!

Stay Connected: Your Guide to May Tech Talks, Office Hours, and Webinars!

Take a look below to explore our upcoming Community Office Hours, Tech Talks, and Webinars this month. This ...

They're back! Join the SplunkTrust and MVP at .conf24

With our highly anticipated annual conference, .conf, comes the fez-wearers you can trust! The SplunkTrust, as ...

Enterprise Security Content Update (ESCU) | New Releases

Last month, the Splunk Threat Research Team had two releases of new security content via the Enterprise ...