Monday, January 13, 2014

cbpolicy email notifier

I come up with a script, that parses maillog and sends email notification to specified admin's email. take a look:

#!/bin/bash
# Usage:
# cbpolicy_notifier <LINES TO PARSE> <MAIL TO>

LINES=$1
MAIL_TO=$2

if [ -z "$2" ] || [ ! -z "$3" ];then
    echo ""
    echo "ERROR: $0 requires number munber of lines to parse and valid email to notify you"
    echo ""
    echo "Usage: $0 <LINES TO PARSE> <MAIL TO>"
    echo ""
    exit
fi

EMAILMESSAGE="/tmp/cbpolicy_notifier_`date +%Y-%m-%d_%H-%M`.txt"
HOST_NAME=$(hostname)
MAIL_FROM=postmaster@$HOST_NAME

for i in `tail -$LINES /var/log/maillog  | grep cbpolicy | grep reject | grep -v "from=root@" | grep "track=Sender" | grep -oP '(?<=from=).*?(?=,)' | uniq`;
do
        echo $i
        V_EMAIL=$i
        MSG_SUBJECT_ADMIN="$HOST_NAME::Outbound email quota was exceeded for $V_EMAIL"
        MSG_SUBJECT_USER="WARNING::Your outbound email hourly quota was exceeded"
        echo "We have encountered outbound email overlimiting for $V_EMAIL" > $EMAILMESSAGE
        echo "" >> $EMAILMESSAGE
        LOG_SAMPLE=$(tail -$LINES /var/log/maillog  | grep cbpolicy | grep reject | grep -v "from=root@" | grep $V_EMAIL )
        echo "This is the log sample" >> $EMAILMESSAGE
        echo "" >> $EMAILMESSAGE
        echo "$LOG_SAMPLE" >> $EMAILMESSAGE
        /bin/mailx -r "$MAIL_FROM" -s "$MSG_SUBJECT_ADMIN" "$MAIL_TO" < $EMAILMESSAGE

        echo "Dear customer." > $EMAILMESSAGE
        echo "" >> $EMAILMESSAGE
        echo "Your hourly outbound email quota was overlimited. Please reduce amount of emails you are sending out." >> $EMAILMESSAGE
        /bin/mailx -r "$MAIL_FROM" -s "$MSG_SUBJECT_USER" "$V_EMAIL" < $EMAILMESSAGE
done
add this to cron, just specify num of lines to parse and email. Like this:
*/15 * * * * /usr/local/sbin/cbpolicy_notifier 500 support@example.com

No comments:

Post a Comment