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!

Index This | I am a number, but when you add ‘G’ to me, I go away. What number am I?

March 2024 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with another ...

What’s New in Splunk App for PCI Compliance 5.3.1?

The Splunk App for PCI Compliance allows customers to extend the power of their existing Splunk solution with ...

Extending Observability Content to Splunk Cloud

Register to join us !   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to ...