电信网通等各ISP运营商IP地址段生成脚本

本文介绍的脚本主要用来生成各ISP运营商的完整IP地址段文件,用于智能DNS服务器,让电信的用户访问电信服务器,让网通的用户访问网通服务器,使用户以最快的速度访问我们提供的服务,以达到良好的用户体验。

01#!/bin/bash
02#
03# Script Name: create_dns_acl_files.sh
04# Description: used for DNS
05#
06# Author: Xinggang Wang - OpsEye.com
07# Create Date: 2011-09-15
08# Last Modified: 2011-09-16
09  
10rootdir=`cd $(dirname $0) && pwd`
12file=ip_apnic
13whois=/usr/bin/whois
14date=`date +%Y%m%d`
15# according to your system performance to tunning this variable.
16threads=300
17  
18cd $rootdir
19  
20rm -f $file
21wget $fileadress -O $file
22  
23rm -rf result/$date
24mkdir -p result/$date/other
25  
26trans_mask()
27{
28 local num=$1
29 cat <<EOF | bc | tail -1
30pow=32;
31define log2(x) {
32if (x<=1) return (pow);
33pow--;
34return(log2(x/2));
35}
36log2($num)
37EOF
38}
39  
40fifofile="/tmp/$$.fifo"
41mkfifo $fifofile
42exec 6<> $fifofile
43for ((i=0;i<$threads;i++));do
44 echo
45done >&6
46  
47export IFS='|'
48grep 'apnic|CN|ipv4|' ip_apnic |
49while read a b c ip cnt d
50do
51 read -u6
52{
53 mask=$(trans_mask $cnt)
54 netname_province=`$whois $ip/$mask@whois.apnic.net|awk '/^netname:/{print $2}'`
55 netname=`echo $netname_province|awk -F- '{print $1}'`
56  
57 printf "%-30s %-20s\n" $ip/$mask $netname_province >> result/$date/all_detail.txt
58  
59 case $netname in
60 CHINANET|UNICOM) echo "$ip/$mask" >> result/$date/$netname.txt
61 ;;
62 *) echo "$ip/$mask" >> result/$date/OTHER.txt
63 echo "$ip/$mask" >> result/$date/other/$netname.txt
64 ;;
65 esac
66  
67 sleep 3
68 echo >&6
69} &
70  
71done
72  
73wait
74exec 6>&-
75rm -f $fifofile
76  
77# create acl files
78until ! ps -ef|grep -v grep |grep -q whois
79do
80 sleep 1
81done
82  
83sleep 1
84  
85mkdir -p result/$date/acl_files
86  
87for i in CHINANET:telecom UNICOM:cnc ;do
88 awk 'BEGIN{print "acl \"'${i#*:}'\" '{'"}{print $1";"}END{print "'}';"}' result/$date/${i%:*}.txt \
89 >result/$date/acl_files/${i#*:}_acl.conf
90  
91done
92  
93exit 0

此段代码来源网络,不知具体作者是哪位,表示遗憾。

此脚本在一般配置的服务器上运行时间大概50多秒,非常有效率。会生成所有ISP运营商的IP地址段文件,并把主要的ISP运行商电信和网通的IP地址段生成acl控制文件,方便直接同步到dns服务器上进行更新。

生成结果展示: