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!

List all IP addresses available on a linux server

This article deals with Linux based systems.

While working with a server with many IP addresses you may need to list all of the IP addresses on the server. Most commands may give you more information than you may need. To get a list of only the IP addresses use the following command:

The IP address available on the server will be displayed in a list like this:

I have found that this makes it easier to cut and paste into a text file and then later add the IPs to a database.