Blocking IP Addresses Of Any Country With iptables
This article explains how you can block IP addresses of any country with the help of iptables.
The API to get the IP addresses to block
First you need to know the code (ISO 3166 format) of the country you would like to block. The full list is available HERE.
Once you have the country code, you can now get the list at the following url (Afghanistan and Argentina in this example):
http://blogama.org/country_query.php?country=AF,AR
If you dont see IP addresses by lines, view the page code.
How often is data updated
During the first week of each month.
The full SQL database
For the full SQL database of this data, please read this page.
Automatic bash script to block those IP addresses in iptables
The following script will:
- Fetch the right IP addresses of the country you would like to block from our API
- Add these rules in iptables.
#!/bin/bash ###PUT HERE COMA SEPARATED LIST OF COUNTRY CODE### COUNTRIES="AK,AR" WORKDIR="/root" ####################################### cd $WORKDIR wget -c --output-document=iptables-blocklist.txt http://blogama.org/country_query.php?country=$COUNTRIES if [ -f iptables-blocklist.txt ]; then iptables -F BLOCKDB="iptables-blocklist.txt" IPS=$(grep -Ev "^#" $BLOCKDB) for i in $IPS do iptables -A INPUT -s $i -j DROP iptables -A OUTPUT -d $i -j DROP done fi rm $WORKDIR/iptables-blocklist.txt