Linux Iptables如何禁止某些国家访问服务器
时间:2019-11-20 08:52:53 来源:igfitidea点击:
如何配置Apache或iptables以拒绝来自某些国家/地区的访问?
如何阻止某个国家/地区访问服务器?
首先,需要获取每个国家/地区的网络IP列表。
然后在Apache或iptables中阻止流量。建议使用iptables,这样可以节省一些资源。
#!/bin/bash
# -------------------------------------------------------------------------------
ISO="af en"
### 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
使用crontab如下安装脚本:
@weekly /path/to/country.block.iptables.sh
执行脚本:
# /path/to/country.block.iptables.sh
是有iptables geoip补丁
另外一种方法是使用geoip iptables补丁。
- 从官方网站获取geoipt补丁。
https://people.netfilter.org/peejix/patchlets/ - 下载并安装Linux内核和iptables源代码。
- 抓取并安装名为patch-o-matic的工具(geoip模块必需)。
http://ftp.netfilter.org/pub/patch-o-matic-ng/snapshot/ - 最后,从MaxMind获取GEO IP数据库。
https://www.maxmind.com/

