Incident & Response with Python Script


Do I have a way, in the community version, to run a python script based on conditions?

Based on the consumption of an API, I would like to block the IP address in the API Gateway. I have created the script but I don’t know how to activate it based on conditions. Greetings.

You can fire off an alert and use a script for notification but that is an Enterprise License Feature. If you are able to stay under 5GB of data per day, you can apply for a Free Enterprise License.

1 Like

Thanks tmacgbay!

I m going to try!

El El mar, 16 mar. 2021 a la(s) 14:33, Tmacgbay via Graylog Community <> escribió:

I create this POC with Graylog, Kong API, Prometheus, Grafana, API & BBDD on Docker-Compose.

I create the License Enterprise and charge! I create, before the Licence, this Script to disable IP con de API Mananger, and allow de Ip after some time.

import time 
import json
import requests
import argparse

parser = argparse.ArgumentParser(
    description='Programa I&R IP Restrinction sobre Kong Server'

parser.add_argument('-i', '--ip', metavar='ip', required=True, help='Direccion IP a Bloquear. Ej: python3')
parser.add_argument('-t', '--time', metavar='time', required=True, help='Tiempo a mantener la Direccion IP a Bloquear. Ej: python3')
args = parser.parse_args()
url = 'http://api.local:8001/services/MyAPI/plugins'

# Contador  
def countdown(t): 
    while t: 
        mins, secs = divmod(t, 60) 
        timer = '{:02d}:{:02d}'.format(mins, secs) 
        print(timer, end="\r") 
        t -= 1
# Bloqueo de Direccion TCP IP
def bloqueo():
    data = {'name':'ip-restriction',
    r =, data)
    data = r.json()
    print ('Bloqueado: %s' % data['config']['deny'])
    return data
# Eliminamos la regla, con ID de Plugin. 
def eliminar(data):
    print('El ID del Plugin es: %s' % data['id'])
    print ('Desbloqueo: %s' % data['config']['deny'])
    r = requests.delete(url + '/' + data['id'])
    return r.status_code

id = bloqueo()
if (eliminar(id) == 204):
    print ('Procedimiento de Bloqueo Exitoso')
    print ('Problemas en el Procedimiento de Bloqueo')

I need to install python, on the docker, for run the script…

How can i send the source_ip of the Alarm to the script?


I haven’t done it but a quick look makes me think that rather than passing the parameter, you will need to iterate through fields in the python script to pull out the source_ip.

I will that! I think the same. Now i need to investigate how can i install python con de container…I use the docker compose…

I still with problems!

I create the script and save it on /usr/share/graylog/scripts

But i can not execute

I dont know, the script have the permission…

What do you think?


I can resolved it.

Is there a way to Debug the program? Or a dataset, model, to play with?


I am glad you resolved it! was it just Linux permissions on the script? There is a debug feature in pipeline code but for an alert scrip I imagine you would have to manually have it write to a log file or something similar. Sorry I am not much help here!

Thanks my friend. Let’s see what happens, create a new thread to see if I’m lucky! I have to learn to loop through the “message” of the event. There is the issue.

I resolved in this way!

#!/usr/bin/env python3
import json
import sys
import time
import requests

url = ‘http://kong:8001/services/MyAPI/plugins

Function that prints text to standard error

def print_stderr(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)

Funcion Extract IP

def extract_ip():
with open(‘log.txt’, ‘r’) as file:
data =’\n’, ‘’)
string = “client_ip”
ip = (data[data.index(string)+11:data.index(string)+26]).strip(’"’’)
return ip

Count Time

def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = ‘{:02d}:{:02d}’.format(mins, secs)
print(timer, end="\r")
t -= 1

Block IP

def bloqueo(client_ip):
data = {‘name’:‘ip-restriction’,
r =, data)
data = r.json()
sys.stdout.write(‘Bloqueado: %s’ % data[‘config’][‘deny’])
return data

Delete API Manager Rule

def eliminar(data):
sys.stdout.write(‘El ID del Plugin es: %s’ % data[‘id’])
sys.stdout.write(‘Desbloqueo: %s’ % data[‘config’][‘deny’])
r = requests.delete(url + ‘/’ + data[‘id’])
return r.status_code

Main Program

if name == “main”:

temp = sys.stdout #store original stdout object for later
sys.stdout = open(‘log.txt’,‘w’) #redirect all prints to this log file

Print out all input arguments.

sys.stdout.write("All Arguments Passed In: " + ’ '.join(sys.argv[1:]) + “\n”)

Turn stdin.readlines() array into a string

std_in_string = ‘’.join(sys.stdin.readlines())


event_data = json.loads(std_in_string)

Extract some values from the JSON.

sys.stdout.write(“Values from JSON: \n”)
sys.stdout.write("Event Definition ID: " + event_data[“event_definition_id”] + “\n”)
sys.stdout.write("Event Definition Title: " + event_data[“event_definition_title”] + “\n”)
sys.stdout.write("Event Timestamp: " + event_data[“event”][“timestamp”] + “\n”)

Extract Message Backlog field from JSON.

for message in event_data[“backlog”]:
for field in message.keys():
sys.stdout.write("Field: " + field + “\t”)
sys.stdout.write("Value: " + str(message[field]) + “\n”)
sys.stdout = temp

Extraigo Direccion IP del log.txt

ip = extract_ip()

Block IP

id_block = bloqueo(ip)

Time Rule Life 50 Seg


Delete the Rule




This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.