Create a gist now

Instantly share code, notes, and snippets.

Auto-ban website spammers via the Apache access_log
#!/bin/bash
#
# Config
#
# if more than the threshold, the IP will be banned
THRESHOLD=100
# search this many recent lines of the access log
LINESTOSEARCH=50000
# term to search for
SEARCHTERM=POST
# logfile to search
LOGFILE=/var/log/httpd/access_log
# email to alert upon banning
ALERTEMAIL=foo@foo.com
#
# Get the last n lines of the access_log, and search for the term. Sort and count by IP, outputting the IP if it's
# larger than the threshold.
#
for ip in `tail -n $LINESTOSEARCH $LOGFILE | grep "$SEARCHTERM" | awk "{print \\$1}" | sort | uniq -c | sort -rn | head -20 | awk "{if (\\$1 > $THRESHOLD) print \\$2}"`
do
# Look in iptables to see if this IP is already banned
if ! iptables -L INPUT -n | grep -q $ip
then
# Ban the IP
iptables -A INPUT -s $ip -j DROP
# Notify the alert email
iptables -L -n | mail -s "Apache access_log banned '$SEARCHTERM': $ip" $ALERTEMAIL
fi
done
@RuiBranco

Can I add 2 simple features in your code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment