Banning ips with Denyhosts and iptables

If you’re looking for a nice way to automatically ban an ip address without specifically doing the iptables command, here’s a nice script to get you started. This script parses the /etc/hosts.deny file and blocks them using iptables.


#!/bin/bash


ROOT_UID=0


E_NOTROOT=67


if [ "$UID" != "$ROOT_UID" ]; then


echo "Must be root to run this script."


exit $E_NOTROOT


fi


iptables -F


echo "The following ips are blocked: " 1> /var/log/block.log


for x in `cat /etc/hosts.deny | grep -v ^# | cut -d ":" -f 2`; do


/usr/share/.scripts/deny.sh $x >> /var/log/block.log


done


exit0;

For ease of use, that script calls another script called deny.sh.


#!/bin/bash


ROOT_UID=0


E_NOTROOT=67


if [ "$UID" != "$ROOT_UID" ]; then


echo "Must be root to run this script."


exit $E_NOTROOT


fi


iptables -I INPUT -s $1 -j DROP


if [ $? != 0 ]; then


echo "block did not work on $1"


exit 1;


fi


echo "$1 was blocked."


exit 0;

Notice that the script first flushes all the current blocked ip addresses so that you don’t accidentally block the ip addresses many times. This could cause many problems if you’re trying to unblock someone.
Have fun and be safe!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.