Article

Table of Contents
Theme:
Was this article helpful?
Try Vultr Today with

$50 Free on Us!

Want to contribute?

You could earn up to $600 by adding new articles.

How To Block IPs From a Country on CentOS 6

Last Updated: Thu, Nov 12, 2015
CentOS Linux Guides System Admin
Archived content

This article is outdated and may not work correctly for current operating systems or software.

Introduction

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.

Prerequisites

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

yum install iptables ipset -y

service 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.

1.png

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

2.png

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.

vi process.sh

Paste the following into the script:

#!/bin/bash

#Script to process ip ranges to ban using IPSet and IPTables

ipset create countryblock hash:net

while 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.

sh process.sh

Finally, save IPTables and reload:

service iptables save

service iptables reload

Conclusion

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 $600 by adding new articles.