Home/Server & Website Managed Operations/Blocking IPs with iptables
Server & Website Managed Operations

Blocking IPs with iptables

IPdeny provides IP address lists organized by country code. For example, you can download cn.zone:
Once you have all the IP addresses for a specific country, blocking them is straightforward. You can write a script to read the cn.zone file line by line and add each IP to iptables:

#!/bin/bash
# Block traffic from a specific country
# written by yunwei123.com

COUNTRY=”cn”
IPTABLES=/sbin/iptables
EGREP=/bin/egrep

if [ “$(id -u)” != “0” ]; then
echo “you must be root” 1>&2
exit 1
fi

resetrules() {
$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -t mangle -F
$IPTABLES -X
}

resetrules

for c in $COUNTRY
do
country_file=$c.zone

IPS=$($EGREP -v “^#|^$” $country_file)
for ip in $IPS
do
echo “blocking $ip”
$IPTABLES -A INPUT -s $ip -j DROP
done
done

exit 0

The above script can be extended to defend against DDoS attacks!

FREE CHECKUP

Free server checkup

We will send a problem checklist and remediation advice within one business day — no obligation to engage.

135 410 16684
Weekdays Mon – Fri 10:00 – 22:00 (UTC+8) · 7×24 emergency response
Call now
CONTACT

Contact Us

How can we help?

* Required