使用 shell从 apnic 获取中国 IP 段

先抄一段 copy 过来的 shell代码

#!/bin/bash
wget http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest
FILE=delegated-apnic-latest
grep "apnic|CN|ipv4" $FILE | awk -F "|" '{print $4,$5}' > IP.txt
AB=`cat IP.txt | wc -l`
pow=32
i=1
while(($i<=$AB));do
        IP=`sed -n ${i}p IP.txt | awk '{print $1}'`
        HOST=`sed -n ${i}p IP.txt | awk '{print $2}'`
        ERHOST=`echo "obase=2;$HOST" | bc`
        HOSTL=`echo ${#ERHOST}`
        let BU=$pow-$HOSTL
        ZQIAN="11111111111111111111111111111111"
        QIAN=`echo ${ZQIAN:0:$BU}`
        MASK=`echo $QIAN$ERHOST`
        STRA=`echo ${MASK:0:8}`
        STRB=`echo ${MASK:8:8}`
        STRC=`echo ${MASK:16:8}`
        STRD=`echo ${MASK:24:8}`
        MASKA=`echo "ibase=2;$STRA" | bc`
        MASKB=`echo "ibase=2;$STRB" | bc`
        MASKC=`echo "ibase=2;$STRC" | bc`
        MASKD=`echo "ibase=2;$STRD" | bc`
        NETMASK=`echo $MASKA.$MASKB.$MASKC.$MASKD`
        BIT=`echo $MASK | grep -o '1' | wc -l`
        echo $IP/$NETMASK
        echo $IP/$NETMASK >> IP.SH
        let i++
done
rm -rf IP.txt $FILE

测试了下发现脚本并不好使,修改了下

#!/bin/bash
wget http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest
FILE=delegated-apnic-latest
grep "apnic|CN|ipv4" $FILE | awk -F "|" '{print $4,$5}' > IP.txt
AB=`cat IP.txt | wc -l`
pow=32
i=1
while(($i<=$AB));do
        IP=`sed -n ${i}p IP.txt | awk '{print $1}'`
        HOST=`sed -n ${i}p IP.txt | awk '{print $2}'`
        HOSTL=`awk 'BEGIN{print log($HOST)/log(2)}'`
        let BU=$pow-$HOSTL
        echo $IP/$BU
        echo $IP/$BU >> IP.SH
        let i++
done
rm -rf IP.txt $FILE

记得debian下要使用chsh 命令把默认 shell 从 dash 改为 bash,不然会找不到 let
如果要修改为 IP 地址/子网掩码的形式,可以使用netmask命令

apt-get install netmask -y

一段小脚本

ips=`cat IP.SH`
for ip in $ips
do
netmask -s $ip >>test.txt
done
sed -i 's/^[[:space:]]*//' test.txt

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注