1

so I am a Python newbie attempting to write a script that will light up a different LED based on the priority level of the latest security alert added to a log file generated by the Suricata Intrusion Detection System... The issue with the script I have now is that it will only read the last log that has been generated before the script is run and light up the according to LED, but not light up different LEDs as more alerts with different levels are added to the log:


    from gpiozero import LED
    from time import sleep

    with open("fast.log") as f:
            last_row = f.readlines()[-1]


    if "[Priority: 2]" in last_row:
            led = LED(18)

            while True:
                led.on()
                sleep(1)
                led.off()
                sleep(1)

    elif "[Priority: 3]" in last_row:
            led = LED(23)

            while True:
                led.on()
                sleep(1)
                led.off()
                sleep(1)

    elif "[Priority: 1]" in last_row:
            led = LED(21)

            while True:
                led.on()
                sleep(1)
                led.off()
                sleep(1)

I am running the script in the background via python3 script.py &

Mohi Rostami
  • 4,434
  • 1
  • 20
  • 39
robreiner
  • 19
  • 1

1 Answers1

3

Move the code that reads the log into your while True: loop. Don't start a new while True: for each LED as it will never terminate.

Now that I'm home and have had a chance to look at this deeper (with a Raspberry Pi to test it on) I've re-written it to use RPi.GPIO (which works).

#!/usr/bin/python3

import RPi.GPIO as g
from time import sleep

g.setmode(g.BCM)
g.setup([18,23,21],g.OUT)

def flashLED(gpioPin):
    g.output(gpioPin,1)
    sleep(0.5)
    g.output(gpioPin,0)
    sleep(0.5)

while True:
    with open("fast.log") as f:
        last_row = f.readlines()[-1]

        # do stuff to light LEDs depending on record read

        if "[Priority: 2]" in last_row:
            flashLED(18)
        elif "[Priority: 3]" in last_row:
            flashLED(23)
        elif "[Priority: 1]" in last_row:
            flashLED(21)
Dougie
  • 5,381
  • 11
  • 22
  • 30