EzProxies

Private proxies

Bash script to block a list of IP addresses using IPTABLES

In this article we show an example of a script that when run will block a list of IP addresses using IPTABLES. This is intended for complete beginners, so I have made sure to write everything out from start to finish. Please let me know if I have missed anything.

Occasionally we will need to block an IP address from one of our servers. Doing this from the command line using IPTABLES is a simple task. What happens though when you have more than one IP that needs blocked, or maybe even 100 IPs that you need to blocked? The answer is to use this Bash script!

Create a text file using your favorite editor. I prefer to use vi, so I would type the following.

This will create a file named ‘block’ in your root directory. Once vi opens the file hit ‘i’ to enter ‘insert’ mode in vi and paste the following script:

Once you paste this hit your ‘esc’ key to exit ‘insert’ mode in vi, and then type ‘:wq’ to save the file and exit vi.

Notice on line one of the script the letters ‘ips’. This will be the name of the file that you will create with the IPs that you want blocked. Type the following:

This will open vi again and create a file named ‘ips’. Type ‘i’ to enter ‘insert’ mode and on each line enter an IP address that you want blocked from your system. So something like this:

You can even block entire subnets like this:

Once you have completed entering the IPs that you want to block hit ‘esc’ and then ‘:wq’ to save and quit. You now need to execute the script. You will need to change the file permissions to ‘774’ to do this. Type the following:

This will change the file permission to allow you to execute the file. Now run the script file. To do this type:

Your script will now run and all of the IPs that you entered in the ‘ips’ file will be blocked from accessing your system!

One response to “Bash script to block a list of IP addresses using IPTABLES”

  1. Jordan says:

    Wow awesome! I used grep to extract a list of ips that had accessed a compromised website and used it to send spam. This made blocking all 180+ of them way easier.

Leave a Reply

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