Fail2ban Daily Email Update
I’ve been working on a solution to ban web crawlers from the constant port sniffing to my self hosted web services. So I started using Fail2ban, which is a great tool for these specific scenarios.
At first, I set up an instant email notification, but after a day I got way too much emails to handle - kept receiving about 5 to 10 emails per hour!! (Damn you hackers!! :smile: ).
So I thought it would be interesting to have a summary report of the bans/unbans during the last hour instead. Basically, Fail2ban writes the new ban/unban action to a file, which is later on read by a script which emails the results and deletes the file.
These are the lines I used for the ban/unban actions.
actionban = printf %%b "<ip> banned at `date '+%%d %%h %%Y %%T'` by <name> for `awk 'BEGIN{ print <bantime> / 3600 }'` hours. https://db-ip.com/<ip> \n" >> /var/log/fail2ban_mail.log
actionunban = printf %%b "<ip> unbanned at `date '+%%d %%h %%Y %%T'` by <name>. https://db-ip.com/<ip> \n" >> /var/log/fail2ban_mail.txt
And here’s the bash script I installed as an hourly cron job.
EMAIL_FROM_CLEAN=[YOUR_FROM_EMAIL_HERE]
EMAIL_FROM="Fail2Ban <${EMAIL_FROM_CLEAN}>"
EMAIL_TO=[YOUR_TO_EMAIL_HERE]
EMAIL_SUBJECT="[Fail2Ban] Daily Summary"
JAILS=$(fail2ban-client status | grep "Jail list" | sed -E 's/`- Jail list://g' | cut -d ',' --output-delimiter=' ' -f1-)
FAIL2BAN_FILE=/var/log/fail2ban_mail.log
if [ ! -f $FAIL2BAN_FILE ]
then
printf "No new bans/unbans.\n"
exit 0
fi
JAILS_STATUS=""
for jail in ${JAILS[@]}
do
JAILS_STATUS+="${jail}\n"
JAILS_STATUS+=$(fail2ban-client status ${jail} | grep 'Banned IP list')
JAILS_STATUS+="\n"
done
printf %b "Subject: ${EMAIL_SUBJECT}
Date: `LC_ALL=C date +"%a, %d %h %Y %T %z"`
From: ${EMAIL_FROM}
To: ${EMAIL_TO}
Hi,\n
Here bans/unbans in the last 24 hours:
Banned: `grep " banned " $FAIL2BAN_FILE | wc -l`
Unbanned: `grep " unbanned " $FAIL2BAN_FILE | wc -l`
Current status per jail:
${JAILS_STATUS}
Regards" | /usr/sbin/sendmail -f "${EMAIL_FROM_CLEAN}" "${EMAIL_TO}"
rm -f ${FAIL2BAN_FILE}
Bam! It’s done.