公司最近也有自建CDN的打算,无意在网上看到一则通过下apnic的数据并进行shell脚本区分的方法。感觉挺方便的,虽然在台机上测试效率有点低,不过服务器上效果应该还不错。可以自动区分电信网通教育网铁通移动_联通ip地址范围,用于做智能DNS解析应该不错。脚本如下:

 1#!/bin/sh
 2# download ip info from apnic website.
 3apnic_ip_info="/home/www/apnic_ip_info"
 4# get all ip list values from apnic.
 5apnic_all_ip="/home/www/apnic_all_ip"
 6# define save ip result directory.
 7save_dir="/home/www"
 8# delete old exist file.
 9if [ -e "$apnic_ip_info" ];then
10rm -f $apnic_ip_info
11fi
12if [ -e "$apnic_all_ip" ];then
13rm -f $apnic_all_ip
14fi
15if [ -e $save_dir/CNC_GROUP ];then
16rm -f $save_dir/CNC_GROUP
17fi
18if [ -e $save_dir/CHINATELECOM_GROUP ];then
19rm -f $save_dir/CHINATELECOM_GROUP
20fi
21if [ -e $save_dir/CERNET_GROUP ];then
22rm -f $save_dir/CERNET_GROUP
23fi
24if [ -e $save_dir/CRTC_GROUP ];then
25rm -f $save_dir/CRTC_GROUP
26fi
27if [ -e $save_dir/CHINAMOBILE_GROUP ];then
28rm -f $save_dir/CHINAMOBILE_GROUP
29fi
30if [ -e $save_dir/CHINAUNICOM_GROUP ];then
31rm -f $save_dir/CHINAUNICOM_GROUP
32fi
33if [ -e $save_dir/OTHERNET_GROUP ];then
34rm -f $save_dir/OTHERNET_GROUP
35fi
36wget -q http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest -O $apnic_ip_info
37grep "apnic|CN|ipv4|" "$apnic_ip_info" | awk -F'|' '{print $4}' > "$apnic_all_ip"
38while read line
39do
40isp_info=`whois $line | grep -E "(mnt-|netname)" | awk '{print $2}' | xargs`
41# CNC
42into_cnc=`echo $isp_info | sed -n '/CNC/p'`
43# CHINATELECOM
44into_chinatelecom=`echo $isp_info | sed -n '/CHINANET/p'`
45# CERNET
46into_cernet=`echo $isp_info | sed -n '/CERNET/p'`
47# CRTC
48into_crtc=`echo $isp_info | sed -n '/CRTC/p'`
49# CHINAMOBILE
50into_cmcc=`echo $isp_info | sed -n '/CMCC/p'`
51# CHINAUNICOM
52into_unicom=`echo $isp_info | sed -n '/UNICOM/p'`
53if [ "${into_cnc}" != "" ];then
54   echo "$line CNC_GROUP" >> ${save_dir}/CNC_GROUP
55elif [ "${into_chinatelecom}" != "" ];then
56     echo "$line CHINATELECOM_GROUP" >> ${save_dir}/CHINATELECOM_GROUP
57elif [ "${into_cernet}" != "" ];then
58     echo "$line CERNET_GROUP" >> ${save_dir}/CERNET_GROUP
59elif [ "${into_crtc}" != "" ];then
60     echo "$line CRTC_GROUP" >> ${save_dir}/CRTC_GROUP
61elif [ "${into_cmcc}" != "" ];then
62     echo "$line CHINAMOBLIE_GROUP" >> ${save_dir}/CHINAMOBILE_GROUP
63elif [ "${into_unicom}" != "" ];then
64     echo "$line CHINAUNICOM_GROUP" >> ${save_dir}/CHINAUNICOM_GROUP
65else
66     echo "$line OTHERNET_GROUP" >> ${save_dir}/OTHERNET_GROUP
67fi
68done<$apnic_all_ip