Alert script notification (Enterprise) to e-mail not working

I am trying to put together a Alert Python script Notification and I have not had much luck at all. I am basing my script from a previous post on how to do it from @Elix but it’s not working. Maybe YOU can look at it and help me to figure out what I am doing wrong?

I know the alert fires off and other notifications can send e-mail… its really that the script fails silently. Here is the script:

#!/usr/bin/env python3

import getopt
import graypy
import logging
import smtplib
import sys

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

gelf_logger = 0

def body_html(evnt_fields):

    try:
        rv = f"""\
       <html>
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <title>Password Lockout</title>

                </head>


                <body>
                <table width="100%" cellpadding="10" cellspacing="0" style="background-color:#f9f9f9;line-height:1">
                   <tbody>
                    <!-- Event Digest Title Bar  -->
                        <th colspan="3" style="background-color:#e6e6e6;line-height:1.5">
                                 - Event Digest - {evnt_fields['timestamp']} - <br> 
                                ACCOUNT LOCKED - <br>
                        </th>
                      <!-- First section quick info/digest on alert  -->
                    <tr>
                            <td>Locked Account:</td>
                            <td>{evnt_fields['winlog_event_data_TargetUserName']}</td>
                    </tr>
                    <tr>
                            <td>Locked From:</td>
                            <td>{evnt_fields['winlog_event_data_TargetDomainName']}</td>
                    </tr>
                    <tr>
                            <td>NOTE:</td>
                            <td>The IT Group has been notified that {evnt_fields['winlog_event_data_TargetUserName']} has been locked out. <br>
                                For immediate assistance you can call the IT Group at #### or e-mail us at email@email.com
                            </td>
                    </tr>
                   </tbody>
                </table>
            </body>
        </html>"""
        
    except KeyError:
        gelf_logger.debug("Exception KeyError in body_html()", exc_info=1)
        sys.exit(10)

    return rv

def body_plain(evnt_fields):
    try:
        rv = f"""
           --------------------------------------------------------------------------------------------------------------------------
                The following account has been locked out:  {evnt_fields['winlog_event_data_TargetUserName']}
            --------------------------------------------------------------------------------------------------------------------------

                    Account locked out : {evnt_fields['winlog_event_data_TargetUserName']}
                    Locked from Server : {evnt_fields['winlog_event_data_TargetDomainName']}

                    NOTE: The IT Group has been notified that {evnt_fields['winlog_event_data_TargetUserName']} has been locked out.
                    
                        For immediate assistance you can call the IT Group at ####### 
                        alternatively,  e-mail us at email@email.com

                   Timestamp: {evnt_fields['event_created']}

            --------------------------------------------------------------------------------------------------------------------------

"""
    except KeyError:
        gelf_logger.debug("Exception KeyError in body_plain()", exc_info=1)
        sys.exit(11)

    return rv

def init_logging():
    global gelf_logger
    handler = graypy.GELFTCPHandler("MyGraylogServer", 12202)
    gelf_logger = logging.getLogger("Log_to_Graylog")
    gelf_logger.setLevel(logging.DEBUG)
    gelf_logger.addHandler(handler)

def parse_cmdline_params(argv):
    longopts = ['winlog_event_data_TargetUserName=',
                'winlog_event_data_TargetDomainName=',
                'user_email=',
                'event_created=']
    argvc = []
    for arg in argv:
        argvc.append(arg.replace("\"", ""))
    try:
        opts, args = getopt.getopt(args=argvc,
                                   shortopts="",
                                   longopts=longopts)
    except getopt.GetoptError:
        gelf_logger("Exception getopt.Getopt in parse_cmdline_params()", exc_info=1)
        sys.exit(12)

    rv = {}
    for opt, arg in opts:
        rv.setdefault(opt[2:], arg)
    return rv

def trigger_email(evnt_fields, relay="mailgateway"):
    try:
        subject = f"ACOUNT LOCKED: {evnt_fields['winlog_event_data_TargetUserName']} from server {evnt_fields['winlog_event_data_TargetDomainName']}"
        msgfrom = "awesomeIT@email.com"
        msgrcpt = f"{evnt_fields['user_email']}"

    except KeyError:
        gelf_logger.debug("Exception KeyError in trigger_email()", exc_info=1)
        sys.exit(13)

    msg = MIMEMultipart("alternative")
    msg['Subject'] = subject
    msg['From'] = msgfrom
    msg['To'] = msgrcpt
    msg.attach(MIMEText(body_plain(evnt_fields), "plain"))
    msg.attach(MIMEText(body_html(evnt_fields), "html"))

    try:
        with smtplib.SMTP(relay) as srv:
            srv.send_message(msg)
    except Exception:
        gelf_logger.debug("Exception in trigger_email()", exc_info=1)
        sys.exit(14)

    return subject, msgrcpt

def main(argv):
    init_logging()
    evnt_fields = parse_cmdline_params(argv)
    subject, msgrcpt = trigger_email(evnt_fields)
    gelf_logger.debug(f"Sucessfully sent email alert with subject {subject} to {msgrcpt}.")
    sys.exit(0)

if __name__ == "__main__":
    main(sys.argv[1:])

and here is how the script is implemented:

I tried following the previous post as close as possible - I even have messier code similar to the above that I can get to run manually with python3 but as soon as I put it into Graylog it chokes.

Its likely something like flip that bit over there… just can’t find that bit. :smiley:

@tmacgbay
Question, I’m labbing this sup , where it states Script path where do you drop the py script? Sorry first time using Enterprise stuff.

EDIT: :laughing: nvm

1 Like

Hi tmacgbay,

about the Script Arguments: Can you try again without dashes and untick the option to send alert data through STDIN?

No luck so far… still puttering with it… The good news is the GELF logging is working! Here is the error I see:

full_message
Traceback (most recent call last):

  File "/etc/graylog/scripts/alert-user-pw-fail.py", line 117, in trigger_email
    subject = f"ACOUNT LOCKED: {evnt_fields['winlog_event_data_TargetUserName']} from server {evnt_fields['winlog_event_data_TargetDomainName']}"

KeyError: 'winlog_event_data_TargetUserName'

Definitely an issue with how I am passing in parameters, More research needed as to how Python wants them to come in… and how Graylog presents them to the scripts… :-\

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