I&R with Python

Create a script to disable an IP address in the API manager and after x amount of minutes re-enable it. I don’t understand how I can keep the client_ip field to be able to execute the methods.

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

# URL de API KONG Manager
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") 
        time.sleep(1) 
        t -= 1
# Bloqueo de Direccion TCP IP
def bloqueo(ip):
    data = {'name':'ip-restriction',
            'config.deny':ip}
    r = requests.post(url, 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
# Function that prints text to standard error
def print_stderr(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

# Principal
if __name__ == "__main__":

    # 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())

    # Load JSON
    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.
    sys.stdout.write("\nBacklog:\n")
    for message in event_data["backlog"]:
        for field in message.keys():
            if (field == "client_ip"):
                sys.stdout.write("Field: " + field + "\t")
                sys.stdout.write("Value: " + str(message[field]) + "\n")
                ip = str(message[field])

    # Bloqueo de Direccion IP
    id = bloqueo(ip)
    # Espero 10 Minutos
    countdown(10)
    # Elimino Regla de Bloqueo
    if (eliminar(id) == 204):
        print ('Procedimiento de Bloqueo Exitoso')
    else:
        print ('Problemas en el Procedimiento de Bloqueo')

    # Return an exit value. Zero is success, non-zero indicates failure.
    exit(0)

The problem its here

# Extract Message Backlog field from JSON.
sys.stdout.write("\nBacklog:\n")
for message in event_data["backlog"]:
    for field in message.keys():
        if (field == "client_ip"):
            sys.stdout.write("Field: " + field + "\t")
            sys.stdout.write("Value: " + str(message[field]) + "\n")
            ip = str(message[field])

Here its de error…

Any idea?

Here the notification:

I need the client_ip :smiley:

Thanks! Guys

Maybe simplier way would be to create field in alert definition, and then get it using:
event_data["event"]["fields"]["field_name"]

Replace field_name with your created field in alert definition.

1 Like

I resolved in this way! Creating a file, log.txt with the message, and take the IP Address. Take a look.

#!/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 = file.read().replace(’\n’, ‘’)
string = “client_ip”
ip = (data[data.index(string)+11:data.index(string)+26])
ip = ip[1:-1]
return ip

Count Time

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

Block IP

def bloqueo(client_ip):
data = {‘name’:‘ip-restriction’,
‘config.deny’:client_ip}
r = requests.post(url, data)
data = r.json()
return data

Delete API Manager Rule

def eliminar(data):
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())

Load JSON

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.

sys.stdout.write("\nBacklog:\n")
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.close()
sys.stdout = temp

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

IP a Bloquear

ip = extract_ip()
sys.stdout.write("Direccion IP: " + ip + “\n”)

Block IP

id_block = bloqueo(ip)
sys.stdout.write("ID del Bloqueo: " + str(id_block[‘id’]) + “/n”)
sys.stdout.close()
sys.stdout = temp

Time Rule Life 1 Minute

countdown(60)

Delete the Rule

eliminar(id_block)

exit(0)

Please post your source code in ` code ` or ``` code ```, because it’s not correctly formated in this forum.

Sorry!

#!/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 = file.read().replace('\n', '')
    string = "client_ip"
    ip = (data[data.index(string)+11:data.index(string)+26])
    ip = ip[1:-1]
    return ip

# Count Time
def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1

# Block IP
def bloqueo(client_ip):
    data = {'name':'ip-restriction',
            'config.deny':client_ip}
    r = requests.post(url, data)
    data = r.json()
    return data

# Delete API Manager Rule
def eliminar(data):
    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())

    # Load JSON
    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.
    sys.stdout.write("\nBacklog:\n")
    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.close()
    sys.stdout = temp

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

    # IP a Bloquear
    ip = extract_ip()
    sys.stdout.write("Direccion IP: " + ip + "\n")

     # Block IP
    id_block = bloqueo(ip)
    sys.stdout.write("ID del Bloqueo: " + str(id_block['id']) + "/n")
    sys.stdout.close()
    sys.stdout = temp
    # Time Rule Life 1 Minute
    countdown(60)

    # Delete the Rule
    eliminar(id_block)

    exit(0)
1 Like

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