How To Block IPs From a Country on CentOS 6


Welcome to another Vultr tutorial. Today we’ll be learning how to use IPTables and IP2Location to block IP addresses from certain countries. IP2Location offers databases of country IP address blocks as a free service.


Before we do anything, we must make sure to have iptables and ipset installed:

yum install iptables ipset -yservice iptables start

Choose countries to block

Visit the IP2Location visitor blocker service. In this example, we’ll be blocking connections from Iceland, so we’ll select Iceland from the list.

How To Block IPs From a Country on CentOS 6

After doing so, select “Linux IPTables” as the output format. It should look like:

How To Block IPs From a Country on CentOS 6

Upload the file to your server with your favorite FTP client. I use FileZilla.

Blocking the IPs

Once the previous step is complete, access SSH on your server and head to the directory where the file was uploaded.

Rename the file to block.txt.

Now we will process the file of IP blocks. Create a shell script.


Paste the following into the script:

#!/bin/bash#Script to process ip ranges to ban using IPSet and IPTablesipset create countryblock hash:netwhile read line; do ipset add countryblock $line; done < (block.txt)iptables -I INPUT -m set --match-set countryblock src -j DROP

Save the file, and exit the text editor.

Run the script.


Finally, save IPTables and reload:

service iptables saveservice iptables reload


You have now successfully blocked a country from accessing your Vultr server. If you want to remove the block, simply remove the rules from IPTables.

Want to contribute?

You could earn up to $300 by adding new articles

Submit your article
Suggest an update
Request an article

No comments

Powered by Blogger.