Simple SSH bruteforce prevention using iptables

Since I like to learn more about scripting, I decided to write my own SSH bruteforce prevention script instead of installing a plug-and-play tool. You can run the script manually or have it run every hour or so using crontab.

As root, create a new directory for the script and files, name it for example bfCheck:

# mkdir bfCheck

In this folder, create a new file, name it for example

# cd bfCheck
# touch

Open the file using nano and copy paste the following script:

# nano -w

blockIPs=”$(cat /var/log/secure | grep “Failed password for” | grep -v “invalid” | awk {‘print $11’} | sort | uniq -c | awk -v limit=50 ‘$1 > limit{print $2}’)”

if [ -z “$blockIPs” ]
echo “No match found, skipping”

while read -r line; do
if grep -q $line <<<$currentIPs
echo “IP address already blocked, skipping. IP: $line”
/sbin/iptables -A INPUT -s $line -p tcp –dport 22 -j DROP
echo “Blocking IP address: $line”
echo `date +”%b %d %H:%M:%S”` Blocking $line >> /root/bfCheck/iptables.log
done <<< “$blockIPs”


Save and close (ctrl+x & y).

Change the file’s mode, give it +x:

# chmod +x

Run the script, you will it will start blocking IP addresses or it will show you that not match is found:

# ./

Please note the limit=50 at the very first line of the script just after #!/bin/sh. You can change it to your wishes, it means that it will only block the IP address if there was more than 50 tries to access your server with an invalid password.