I finally modified the script slightly to keep a list of the “bad” IP addresses in a text file. Please feel free to modify the script any way you like and I’d really appreciate any modifications anyone might have.

#!/bin/sh
# $Author: pankaj $
# $Date: 2005/01/27 18:58:27 $
# $Revision: 1.2 $
#
# This is a simple script to parse /var/log/secure for ssh hacking attempts and block the whole subnet
# It might be a little overzealous but so what
#
#
for i in `grep 'Failed password' /var/log/secure | egrep -v '|' | awk '{print \$11 \$13}' | cut -d ':' -f 4| cut -d '.' -f 1-3 | uniq | egrep -v '172.20.16'`
do
BLOCK=${i}.0/24
echo "Blocking ${i}.0"
echo "${i}.0" >> /usr/local/share/blocked/ipaddresses.txt
done

mv /usr/local/share/blocked/ipaddresses.txt /tmp/ipaddresses.txt
cat /tmp/ipaddresses.txt | sort | uniq > /usr/local/share/blocked/ipaddresses.txt
rm -f /tmp/ipaddresses.txt
#
#/sbin/iptables --flush

for i in `cat /usr/local/share/blocked/ipaddresses.txt | sort | uniq`
do
/sbin/iptables -I INPUT -s ${i}/24 -j DROP
done
#/etc/init.d/iptables restart

# $Log: blocksshhacks.sh,v $
# Revision 1.2  2005/01/27 18:58:27  pankaj
# *** empty log message ***