用 iptables 屏蔽来自某个国家的 IP

14 年 ago jony 7

方法一:

方法很容易,先到 IPdeny 下载以国家代码编制好的 IP 地址列表,比如下载 cn.zone:

# wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone

有了国家的所有 IP 地址,要想屏蔽这些 IP 就很容易了,直接写个脚本逐行读取 cn.zone 文件并加入到 iptables 中:

#!/bin/bash
# Block traffic from a specific country

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

好 IP 和坏 IP 都被屏蔽掉了,这种办法当然不高明,屏蔽 IP 也没有解决被攻击的问题,但是是解决问题的第一步,屏蔽了攻击源以后我们才有带宽、时间和心情去检查 VPS 的安全问题。公布一份我们客户被攻击的网络流量图,在18点到0点所有带宽都被攻击流量占用,这时候客户无法登录 VPS,访问者也无法访问网站:

方法二:

加到网站根目录的index.php中即可

$ly_lan = strtolower(substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,5));
if ($ly_lan == "zh-cn") {
header('HTTP/1.1 503 Method Not Allowed');
echo '<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body bgcolor="white">
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>nginx/0.8.54</center>
</body>
</html>';
exit;
}

通过判断访问者浏览器语言来拒绝访问

方法三:

在根目录的.htaccess文件中加入地区IP区域

http://www.countryipblocks.net/country-blocks/select-formats/