iptables屏蔽/放行某国ip

原文转自 http://www.fomore.net/os/?p=361
方法很容易,先到 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

——————————–分割线————————————
我在这个基础上做了一个改进的脚本,自用

#!/bin/bash
# update iptables for china
ipt="iptables -t nat -A SHADOWSOCKS -d "
tails=" -j RETURN"
rm ./cn.zone*
rm ./tmp_iptables*
cat>tmp_iptables<<eof
#!/bin/bash
# Create new chain
iptables -t nat -N SHADOWSOCKS
iptables -t nat -A PREROUTING -p tcp -j SHADOWSOCKS
# Ignore your shadowsocks server's addresses
# It's very IMPORTANT, just be careful.
iptables -t nat -A SHADOWSOCKS -d xxx.xxx.xxx.xxx -j RETURN #xxx是server地址
iptables -t nat -A SHADOWSOCKS -d xxx.xxx.xxx.xxx -j RETURN # 这一步非常重要!到服务端的出口数据不要再进行重定向,否则进入死循环
#去除内网地址
iptables -t nat -A SHADOWSOCKS -d 0.0.0.0 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 127.0.0.1 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 114.114.114.114 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 8.8.8.8 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 192.168.1.0/24 -j RETURN #过滤国内流量 eof wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone for c in `cat cn.zone` do z=$ipt$c$tails echo $z >>./tmp_iptables
done cat>>tmp_iptables<<eof
# Anything else should be redirected to shadowsocks's local port
iptables -t nat -A SHADOWSOCKS -p tcp -j REDIRECT --to-ports 1080 # Apply the rules
#iptables -t nat -A OUTPUT -p tcp -j SHADOWSOCKS
# 对于本机全局代理必须是加入到OUTPUT链中 eof mv tmp_iptables tmp_iptables.sh exit 0 
上一篇
下一篇