Blacklisting range of IPs using iptables: the quick and dirty way

Let’s suppose you have a list with IPs you want to block on your router, for example from

You can easily convert each line to an iptables command using regular expressions. On a Windows machine you can use Notepad++ for this purpose. Select Search > Replace, tick the regular expression checkbox as seen on this screenshot:


Fill in the fields as below:

Find what: ^(.*)$
Replace with: iptables -I FORWARD -s \1 -j logdrop

After pressing Replace All, you get

iptables -I FORWARD -s -j logdrop
iptables -I FORWARD -s -j logdrop
iptables -I FORWARD -s -j logdrop
iptables -I FORWARD -s -j logdrop

As you can see, it will add a logdrop rule in the forward chain for each IP entry. In case you want to drop the packages not on your router, but on your end-point machine, change FORWARD to INPUT. Also, you can simply use drop instead of logdrop. Watch out for the last line of your text file! It must not be empty, otherwise you end up with having “iptables -I FORWARD -s -j logdrop” there. Having the commands ready, you can just copy&paste into the command line, or save it as a bash file.

Alternatively, on a Linux machine you can do all the above in the command line


To check the number of lines, you can use

wc -l

Right now I get 4956 lines.

Run the following script to get another runnable script with all the iptables commands, as above (

echo 'Generating iptables commands'
echo "#!/bin/ash" <<
while read ip; do
echo "iptables -I FORWARD -s ${ip} -j logdrop" <<
done <$1
chmod +x

Usage example: ./, then ./!

Have fun!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s