Skip to content

Instantly share code, notes, and snippets.

@U039b
Last active July 24, 2024 18:48
Show Gist options
  • Save U039b/7aecfaab319c1b4e9d03fdd91970258c to your computer and use it in GitHub Desktop.
Save U039b/7aecfaab319c1b4e9d03fdd91970258c to your computer and use it in GitHub Desktop.
Fail2Ban mail report
#!/bin/bash
# Weekly Fail2Ban Report
# Be sure to sudo chmod +x script_name.sh to make it executable
# Original script from https://www.mopar4life.com/fail2ban-weekly-report-script/
FAIL2BAN_PATH="/var/log/fail2ban*"
LOGFILE="/var/log/custom_fail2ban_report_$(date +%m%d%Y).log"
MAILTOADDRESS="[email protected]"
SUBJECT="$HOSTNAME Weekly Fail2Ban Report"
echo $(date +%m/%d/%Y) > $LOGFILE
echo '' >> $LOGFILE
echo '' >> $LOGFILE
echo 'Most frequently banned IP addresses' >> $LOGFILE
echo ' Count IP Address' >> $LOGFILE
echo '_______________________________________' >> $LOGFILE
# show only the most problomatic IP Addresses
zgrep -h "Ban " $FAIL2BAN_PATH* | awk '{print $NF}' | sort | uniq -c | sort -n | tail | sort -nr >> $LOGFILE
## Generate GeoIP report
echo '' >> $LOGFILE
echo '' >> $LOGFILE
echo '' >> $LOGFILE
echo 'GeoIP' >> $LOGFILE
echo '_____' >> $LOGFILE
for ip in `zgrep -h "Ban " $FAIL2BAN_PATH* | awk '{print $NF}' | sort | uniq -c | sort -n | tail -n15 | sort -nr| awk '{print $2}'`; do
geo=`geoiplookup -l $ip | cut -d ':' -f2`
echo -e "$ip \t $geo" >> $LOGFILE
done
echo '' >> $LOGFILE
echo '' >> $LOGFILE
echo '' >> $LOGFILE
echo 'All banned IP addresses with service type' >> $LOGFILE
echo '_______________________________________' >> $LOGFILE
# Show what service the IP was banned from and how many times for all log files including rotated
# Sorts from high to low (using sort -nr) to sort low to high replace -nr with -n
# To not use WILDCARD (*), you much change from {print $11,$9} to {print $10,$8}
# SAMPLE OUTPUT
# 1 XXX.71.214.66 [ssh-iptables]
# 1 XXX.62.36.219 [sendmail]
# 2 XX.165.195.40 [vsftpd]
grep "Ban " $FAIL2BAN_PATH* | awk -F[\ \:] '{print $11,$9}' | sort | uniq -c | sort -nr >> $LOGFILE
# EMail File after completion (wait 10 seconds to finish writing log first)
sleep 10
mail -s "$SUBJECT" "$MAILTOADDRESS" < $LOGFILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment