Alerting

Running php script in alert with adding results as arguments

damiko
Communicator

Hello Ninjas!
I need help with setting an alert which triggers a php script with results. This script should pass the results to 3rd party system.
For example: script.php "date | field1 | field 2 | _raw "

0 Karma
1 Solution

manjunathmeti
Champion

Step 1. Place script my_script.php in $SPLUNK_HOME/etc/apps/[app]/bin/.

Step 2: Create php.path file in $SPLUNK_HOME/etc/apps/[app]/bin/ or in $SPLUNK_HOME/bin/ with below content (path to binary) and make it executable.

/usr/bin/php

Step 3. Create app.conf and alert_actions.conf in $SPLUNK_HOME$/etc/apps/[app]/default/ with below configurations. Note that name of the script should be the same as in its alert_actions.conf stanza.

app.conf:

[ui]
is_visible = 0
label = My Alert Action

[launcher]
description = My Alert Action
version = 1.0.0

[install]
state = enabled
is_configured = 1

alert_actions.conf

[my_script]
is_custom = 1
label = My Alert Action
disabled = 0
alert.execute.cmd = php.path
alert.execute.cmd.arg.0 =  $SPLUNK_HOME/etc/apps/[app]/bin/my_script.php
alert.execute.cmd.arg.1 = $trigger_date$
alert.execute.cmd.arg.2 = $result.field1$
alert.execute.cmd.arg.3 = $result.field2$
alert.execute.cmd.arg.4 = $result._raw$

Note that $result.field1$, $result.field2$ and $result._raw$ are the field values from the first row of the search results.

Step 4. Configure alert with this alert action:
savedsearches.conf

[alert_name]
action.my_script = 1

Script will be executed like this:
/usr/bin/php $SPLUNK_HOME/etc/apps/[app]/bin/my_script.php $trigger_date$ $result.field1$ $result.field2$ $result._raw$

View solution in original post

manjunathmeti
Champion

Python script runs php script like below:

/usr/bin/php /opt/splunk/etc/apps/alert_action/bin/my_script.php "2020-02-24 | 404 | /mail-app/api/v2/subscription | 82.200.xx.xx - text message"

Check if this command works.

damiko
Communicator

Yeah this works when I'm running it from cmd line.
alt text

Any method to troubleshoot my alert?

0 Karma

manjunathmeti
Champion

Replace content of python script with below code and check. Now this code directly reads results file.

#!/usr/bin/python
import sys
import subprocess
import json
import csv
import gzip
if __name__ == "__main__":
    rows = []
    if len(sys.argv) < 2 or sys.argv[1] != "--execute":
        print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)"
        sys.exit(1)
    settings = json.loads(sys.stdin.read())
    config = settings['configuration']
    results_file = settings['results_file']
    trigger_date = config.get('trigger_date')
    try:
        with gzip.open(results_file.rstrip('\r\n'), 'rb') as rfile:
            reader = csv.DictReader(rfile, lineterminator="\n")
            for row in reader:
                rows.append({str(k): v for k, v in row.items() if not k.startswith("__mv_")})
    except Exception as e:
        print("Reading %s failed. Error: %s" % (results_file, e))
        sys.exit(2)
    for row in rows:
        inputs = "%s | %s | %s | %s" % (trigger_date, row['status'], row['uri_path'], row['_raw'])
        command = "%s %s %s" % ("/usr/bin/php", "/opt/splunk/etc/apps/alert_action/bin/my_script.php", inputs)
        try:
            p = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            out, error = p.communicate()
            if error:
                print(error)
            if out:
                print(out)
        except Exception, e:
            print ("ERROR Unexpected error: %s" % e)
            sys.exit(3)

damiko
Communicator

changed code in my_script.py. However still blank fields.
from _internal: 02-24-2020 16:23:30.752 +0600 INFO sendmodalert - action=my_script - Alert action script completed in duration=7905 ms with exit code=0

alt text

alt text

0 Karma

manjunathmeti
Champion

I am getting this command splunk logs. Looks like input parameter to php script should be in quotes. Check if below command works.

/usr/bin/php /opt/splunk/etc/apps/alert_action/bin/my_script.php '2020-02-24 | 200 | /servicesNS/nobody/splunk_app_for_nix/saved/searches/fired_alerts/notify | 127.0.0.1 - splunk-system-user [24/Feb/2020:10:40:05.115 +0000] "POST /servicesNS/nobody/splunk_app_for_nix/saved/searches/fired_alerts/notify?trigger.condition_state=1 HTTP/1.1" 200 1981 - - - 5ms'

If this works, use below code and check:

#!/usr/bin/python
import sys
import subprocess
import json
import csv
import gzip
if __name__ == "__main__":
    rows = []
    if len(sys.argv) < 2 or sys.argv[1] != "--execute":
        print >> sys.stderr, "FATAL Unsupported execution mode (expected --execute flag)"
        sys.exit(1)
    settings = json.loads(sys.stdin.read())
    config = settings['configuration']
    results_file = settings['results_file']
    trigger_date = config.get('trigger_date')
    try:
        with gzip.open(results_file.rstrip('\r\n'), 'rb') as rfile:
            reader = csv.DictReader(rfile, lineterminator="\n")
            for row in reader:
                rows.append({str(k): v for k, v in row.items() if not k.startswith("__mv_")})
    except Exception as e:
        print("Reading %s failed. Error: %s" % (results_file, e))
        sys.exit(2)
    for row in rows:
        inputs = "'%s | %s | %s | %s'" % (trigger_date, row['status'], row['uri_path'], row['_raw'])
        command = "%s %s %s" % ("/usr/bin/php", "/opt/splunk/etc/apps/alert_action/bin/my_script.php", inputs)
        try:
            p = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            out, error = p.communicate()
            if error:
                print(error)
            if out:
                print(out)
        except Exception, e:
            print ("ERROR Unexpected error: %s" % e)
            sys.exit(3)

damiko
Communicator

Nevermind, I've deleted spaces on each row. Now it's WORKING! Great! Thank you @manjunathmeti
What changes I could make in your python code to add more fields? alt text

0 Karma

manjunathmeti
Champion

That's great! You can update variable inputs in the code:

inputs = "'%s | %s | %s | %s | %s | %s | %s'" % (trigger_date, row['status'], row['uri_path'], row['_raw'], row['MORE_FIELD_1'], row['MORE_FIELD_2'], row['MORE_FIELD_3'])

And add MORE_FIELD_1, MORE_FIELD_2 and MORE_FIELD_3 in search.

damiko
Communicator

Hey, @manjunathmeti ! I've got a problem, can't add new fields to script. Below is changes I made in your code and Errors I'm getting in _internal

for row in rows:
        inputs = "'%s | %s | %s | %s | %s | %s | %s'" % (trigger_date, row['status'], row['uri_path'], row['_raw'], row['description'], row['ftime'], row['service'])
        command = "%s %s %s" % ("/usr/bin/php", "/opt/splunk/etc/apps/alert_action_php/bin/my_script.php", inputs)

alt text

0 Karma

manjunathmeti
Champion

There is a KeyError: 'description'. It means description field is not there in your search results. Make sure all the fields you are adding are there in search results.

0 Karma

damiko
Communicator

No worries, I forgot to add params in alert_action.conf. It's working now

0 Karma

damiko
Communicator

It's in my search query. I've added them in |table command. Mb I need to add them in alert_action.conf? result.description and etc

0 Karma

damiko
Communicator

Ok, thanks, will try later!

0 Karma

damiko
Communicator

Now I'm receiving this WARN
please check the image
alt text

0 Karma

manjunathmeti
Champion

There is an indentation error in the script. Copy python code as it is and remove first space from each line.

damiko
Communicator

Thank you manjunathmeti. The environment where I was testing it is blocked on weekend, I'll try your python method on Monday. Have a good weekend 🙂

0 Karma

damiko
Communicator

Hey, thank you. I didn't finish setting yet, wanted to ask you: Where do I put savedsearches.conf?
Or should I change current savedsearches.conf?

0 Karma

manjunathmeti
Champion

You should change existing savedsearches.conf.

Get Updates on the Splunk Community!

.conf24 | Registration Open!

Hello, hello! I come bearing good news: Registration for .conf24 is now open!   conf is Splunk’s rad annual ...

ICYMI - Check out the latest releases of Splunk Edge Processor

Splunk is pleased to announce the latest enhancements to Splunk Edge Processor.  HEC Receiver authorization ...

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...