I recently noticed a large number of brute-force hack attempts on my SMTP and SSH servers, and I found it cumbersome to type out the iptables commands every time I wanted to single out a certain IP address for banning or unbanning. I made a simple script to help with the task.

Paste this code into a blank file named “banip” and save, then chmod it executable (755). Henceforth, if you wanted to ban for example 192.168.5.5, all you have to do is use “./banip¬†192.168.5.5“. To unban, use the -u option,¬†“./banip -u 192.168.5.5“. To list all currently banned IPs, use -l.

 

#!/bin/bash

function help {
	echo "Syntax: $0 -[l][u] target(s)"
	echo " Parameters come first. Target is expressed as a IP address."
	echo " No specified parameter will ban the IP."
	echo " -l to list currently banned IPs."
	echo " -u to unban IP(s)."
	exit 1
}

# If no arguments are passed, call the "help" function.
if [ -z "$1" ]; then
	help
fi

# Define some variables
ACTION="-A"
txtred=$(tput setaf 1)
txtyel=$(tput setaf 3)
txtcya=$(tput setaf 6)
txtrst=$(tput sgr0)

while getopts "hul" OPTION
do
	case $OPTION in
		h)
			help
			;;
		u)
			ACTION="-D"
			shift $(($OPTIND - 1))
			;;
		l)
			ACTION="-L"
			shift $(($OPTIND - 1))
			;;
		\?)
			help
			;;
	esac
done

if [ $ACTION == "-L" ]; then
	echo $txtcya"List of Banned IPs:"$txtrst
	iptables -L INPUT -v -n | grep DROP
else
	# ban work loop
	for ZTARGET in "$@"
	do
		echo $txtcya"Applying action $txtred$ACTION$txtcya to $txtyel$ZTARGET"$txtrst
		iptables $ACTION INPUT -s $ZTARGET -j DROP
	done
fi