Created
January 25, 2012 04:19
-
-
Save nicjansma/1674688 to your computer and use it in GitHub Desktop.
Auto-ban website spammers via the Apache access_log
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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
Can I add 2 simple features in your code?