Skip to content

Instantly share code, notes, and snippets.

@nicjansma
Created January 25, 2012 04:19
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nicjansma/1674688 to your computer and use it in GitHub Desktop.
Save nicjansma/1674688 to your computer and use it in GitHub Desktop.
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
Copy link

ghost commented Jul 9, 2014

Can I add 2 simple features in your code?

Copy link

ghost commented Oct 27, 2021

This is amazing, I modified it a bit for my needs. Very clear comments, thank you very much!

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