# BY kerryhu
# QQ:263205768
# MAIL:king_819@163.com
# BLOG:http://kerry.blog.51cto.com
因业务发展需要要阻止一些地区的IP访问服务器,在此将获取IP到用ipsec阻断的过程记录下来,以下就以香港地区为例
1、获取要阻止地区的IP信息
cat get_tw_ip.sh
#!/bin/sh
FILE=./ip_apnic
CNFILE=./hk_apnic
ipinfo=./ipfile.txt
rm -f $FILE
rm -f $CNFILE
wget http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest -O $FILE
grep 'apnic|HK|ipv4|' $FILE | while read text
do
echo $text>> $CNFILE
done
grep 'apnic|HK|ipv4|' $CNFILE | cut -f 4,5 -d'|'|sed -e 's/|/ /g' | while read ip cnt
do
echo $ip:$cnt
mask=$(cat << EOF | bc | tail -1
pow=32;
define log2(x) {
if (x<=1) return (pow);
pow--;
return(log2(x/2));
}
log2($cnt)
EOF
)
echo $ip/$mask>> ./hk.txt
echo $ip>> ./ip.txt
done
hk.txt为获取的香港地区IP信息
2、合并IP信息
使用subnettools.exe工具对获取的IP信息进行合并
3、利用shell脚本生成ipsec批处理
cat netsh_ipsec.sh
#!/bin/sh
file=./hk1.txt
cat $file | awk -F/ '{print $1,$2}'| while read ip mask
do
echo "rem 添加安全策略名称" >> ./deny_hk.bat
echo "netsh ipsec static add policy name=HK" >> ./deny_hk.bat
echo "rem 添加 IP筛选器列表" >> ./deny_hk.bat
echo "netsh ipsec static add filterlist name=No" >> ./deny_hk.bat
echo "rem 添加筛选器到IP筛选器列表(拒绝列表)" >> ./deny_hk.bat
echo "netsh ipsec static add filter filterlist=No srcaddr=$ip dstaddr=me srcmask=$mask description=拒绝香港IP访问 protocol=any" >> ./deny_hk.bat
echo "rem 添加筛选器操作" >> ./deny_hk.bat
echo "netsh ipsec static add filteraction name=deny action=block" >> ./deny_hk.bat
echo "rem 创建一个链接指定 IPSec 策略、筛选器列表和筛选器操作的规则(加入规则到我的安全策略)" >> ./deny_hk.bat
echo "netsh ipsec static add rule name=拒绝规则 policy=HK filterlist=No filteraction=deny" >> ./deny_hk.bat
echo "rem 激活我的安全策略" >> ./deny_hk.bat
echo "netsh ipsec static set policy name=HK assign=y" >> ./deny_hk.bat
done
执行deny_hk.bat自动生ipsec策略,这样就完成了对香港地区IP的屏蔽