前些年有一次想封锁某些地区的IP,当时是用nginx处理的,突然想起来这事。做个记录
首先通过纯真IP数据库查询出某一地区的IP段保存到一个txt里
处理一下,我们只需要查询结果的前两列
cat ip.txt |awk '{print$1,$2}' >ips.txt
把空格替换为冒号
sed -i 's/ /:/g' ips.txt
使用netmask命令来转换,在debian下直接安装即可
apt-get install netmask -y
一段小脚本
ips=`cat ips.txt`
for ip in $ips
do
netmask -c $ip >>test.txt
done
输出的文件里前面有不规则的空格,使用sed删掉。
sed -i 's/^[[:space:]]*//' test.txt
如果要使用iptables屏蔽这些IP段
sed -i '/./{s/^/iptables -I INPUT -s /;s/$/ -j DROP/}' test.txt
Nginx格式
sed -i '/./{s/^/deny /;s/$/;/}' test.txt
OK 处理好了,但是这个列表非常庞大,我们来处理一下,采取了一个笨办法,取出/16到/24的段,然后把/25到/32的段全部处理成/24.不知道有没有更好的办法.脚本如下
iprange=$(cat test.txt)
for ipa in $iprange
do
if [ "${ipa: -3}" = "/16" ];then
echo /16 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/17" ];then
echo /17 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/18" ];then
echo /18 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/19" ];then
echo /19 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/20" ];then
echo /20 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/21" ];then
echo /21 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/22" ];then
echo /22 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/23" ];then
echo /23 is find
echo $ipa >> newip.txt
elif [ "${ipa: -3}" = "/24" ];then
echo /24 is find
echo $ipa >> newip.txt
else
echo no 16-24
fi
#echo ${ipa: -3}
done
cat test.txt|grep -v '/16\|/17\|/18\|/19\|/20\|/21\|/22\|/23\|/24' > newtest.txt
otheriprange=$(cat newtest.txt)
for i in $otheriprange
do
ipa=$(echo $i | cut -f 1,2,3 -d .)
ipb='.0/24'
ipc=$ipa$ipb
echo $ipc >>otheriprange.txt
done
sort otheriprange.txt |uniq > otheriprangeok.txt
cat newip.txt otheriprangeok.txt > banip.txt
rm -rf newip.txt
rm -rf newtest.txt
rm -rf otheriprangeok.txt