Linux Iptables按国家划分
时间:2020-01-09 10:37:30 来源:igfitidea点击:
如何配置Apache或iptables以拒绝与某些国家/地区的连接?
您可以同时在Apache或iptables级别阻止流量。
我建议使用iptables来节省一些资源。
首先,您需要获取每个国家/地区的网络块列表。
只需访问此页面,即可下载CIDR格式的IP阻止文件。
使用以下shell脚本:
"警告!"来自其他国家/地区的人们可能会使用代理服务器,或者想到欺骗其IP地址。
在这种情况下,这可能行不通,只会保护您的邮箱免受自动扫描或垃圾邮件的侵害。
#!/bin/bash
# Purpose: Block all traffic from AFGHANISTAN (af) and CHINA (CN). Use ISO code. #
# See url for more info - http://www.theitroad.local/faq/?p=3402
# Author: theitroad <www.theitroad.local> under GPL v.2.0+
# ------------------------------------------------------------------------------
ISO="af cn"
### Set PATH ###
IPT=/sbin/iptables
WGET=/usr/bin/wget
EGREP=/bin/egrep
### No editing below ###
SPAMLIST="countrydrop"
ZONEROOT="/root/iptables"
DLROOT="http://www.ipdeny.com/ipblocks/data/countries"
cleanOldRules(){
$IPT -F
$IPT -X
$IPT -t nat -F
$IPT -t nat -X
$IPT -t mangle -F
$IPT -t mangle -X
$IPT -P INPUT ACCEPT
$IPT -P OUTPUT ACCEPT
$IPT -P FORWARD ACCEPT
}
# create a dir
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT
# clean old rules
cleanOldRules
# create a new iptables list
$IPT -N $SPAMLIST
for c in $ISO
do
# local zone file
tDB=$ZONEROOT/$c.zone
# get fresh zone file
$WGET -O $tDB $DLROOT/$c.zone
# country specific log message
SPAMDROPMSG="$c Country Drop"
# get
BADIPS=$(egrep -v "^#|^$" $tDB)
for ipblock in $BADIPS
do
$IPT -A $SPAMLIST -s $ipblock -j LOG --log-prefix "$SPAMDROPMSG"
$IPT -A $SPAMLIST -s $ipblock -j DROP
done
done
# Drop everything
$IPT -I INPUT -j $SPAMLIST
$IPT -I OUTPUT -j $SPAMLIST
$IPT -I FORWARD -j $SPAMLIST
# call your other iptable script
# /path/to/other/iptables.sh
exit 0
将上述脚本另存为root用户,并自定义ISO变量以使用ISO国家名称指出国家名称。
完成后,使用crontab如下安装脚本:
@weekly /path/to/country.block.iptables.sh
要立即开始阻止,请输入:
# /path/to/country.block.iptables.sh
这样就可以将整个国家/地区从您的服务器中屏蔽出来。
iptables geoip补丁
上述shell脚本的另一种替代方法是使用geoip iptables补丁。
这不是标准的iptables模块。
您需要下载补丁并编译Linux内核。
- 从官方网站获取geoipt补丁。
- 下载并安装Linux内核和iptables源代码。
- 抓取并安装名为patch-o-matic的工具(geoip模块必需)。
- 最后,从MaxMind获取GEO IP数据库。
内核编译和iptables修补的详细信息不在本教程的范围之内。

