How To Add A List Of IP Addresses To IPtables Using Bash Script

Say you have a list of IP Addresses that you would like to blacklist from trying to access your server. Whether you are preventing intruders or bots from accessing such services like SSH or your website. You want to make a simple list that parses IP addresses and adds them into IPtables. Here’s how you can do such a thing.

We will be creating a simple bash script and a file containing our list of IP addresses. Let’s go ahead and do that with the following:

touch IPLIST

If you didn’t already know, the touch command allows us to create a blank file with the default permissions set via umask.

Now lets go ahead and use our favorite text editor to create our bash script:

nano ./listadd.sh

In our script we are going to start off by adding the shebang.

#!/bin/bash

This allows for the script to be run. Afterwards, in order to take from whats within the IPLIST file and then add each line into IPtables, we are going to do it like this:

while IPS=read -r ip do
iptables -A INPUT -s $ip -j REJECT
done <"./IPLIST"

exit 1

What this does is run a while loop. The read -r command will grab each line from the IPLIST file, places it in the ip variable, and adds a single Iptables entry. The loop will repeat until all lines have been processed.

You will now want to use your preferred text editor to add IP addresses into the IPLIST file. If you are looking for specific lists such as countries, feel free to use https://www.countryipblocks.net/acl.php as a reference.

Your IPLIST file should look like this, for example:

192.168.1.72
192.168.1.90
192.168.4.0/24
192.168.8.7

When you’re done, don’t forget to make it an executable.

chmod +x ./listadd.sh

And then:

./listadd.sh

If everything went all according to plan, you should see all IP addresses in the IPLIST file added to Iptables.