# 利用Python2脚本获取亚太区任意国家的IP段

- Link: https://www.xuepaijie.com/html/skill/devops/807.html
- Published: 2017-02-13T17:27:47+08:00
- Author: Admin

有时候我们需要得到一份某区域的IP段，例如防火墙上使用。通过APNIC的地址库得到数据，
会比较准确权威，且IP库每天都在更新中。

    ```html;
    import os  
    import sys  
    import socket  
    import math  
    import urllib  
    import urllib2  
    import struct  
    import tempfile  

    local_file = os.path.dirname(tempfile.mktemp()) + '/apnic_ip.txt'  

    def _usage():  
        print 'Usage:'  
        print '\t%s <area> [Options]\n' % os.path.basename(sys.argv[0])  
        print 'area example: hk,jp,cn,us,sg etc..'  
        print 'Options:'  
        print ' -ipv4\t\tGet ipv4 address, default.'  
        print ' -ipv6\t\tGet ipv6 address.'  
        print ' -all\t\tGet all address info.'  
        print ' -new\t\tFrom internet get a new info.'  
        print ' -mask\t\teg: x.x.x.x/24, default.'  
        print ' -part\t\teg: x.x.x.x-x.x.x.x'  
        print '\nExample:'  
        print ' %s hk -new\t\t' % os.path.basename(sys.argv[0])  

    def getApnicFile():  
        print 'Downloading files...'  
        try:  
            req = urllib2.Request('ftp://ftp.apnic.net/public/apnic/stats/apnic/delegated-apnic-latest')  
            response = urllib2.urlopen(req)  
            the_page = response.read()  
            fs = open(local_file,'w')  
            fs.write(the_page)  
            fs.close()  
        except:  
            print '[-] Download error!'
            return False  
        return True  

    def viewPartInfo(location,itype):  
        fs = open(local_file,'r')  
        for line in fs:  
            if line[0] == '#':  
                continue  
            list = line.split('|')  
            if list[1] != location :  
                continue  
            if itype != 3:  
                if itype == 1:  
                    if list[2] != 'ipv4':  
                        continue  
                elif itype == 2:  
                    if list[2] != 'ipv6':  
                        continue  
                else:  
                    if list[2] != 'ipv4':  
                        continue  
            else:  
                if list[2] == 'asn':  
                    continue  
            if list[2] == 'ipv6':  
                print '%s/%s' % (list[3],list[4])  
            elif list[2] == 'ipv4':              
                iStart = socket.ntohl(struct.unpack('I',socket.inet_aton(list[3]))[0]) + 1  
                iEnd = iStart + int(list[4]) - 3  
                print '%s-%s' % (socket.inet_ntoa(struct.pack('I',socket.htonl(iStart))),socket.inet_ntoa(struct.pack('I',socket.htonl(iEnd))))  
        fs.close()  

    def viewMaskInfo(location,types):  
        fs = open(local_file,'r')  
        for line in fs:  
            if line[0] == '#':  
                continue  
            list = line.split('|')  
            if list[1] != location:  
                continue  
            if itype != 3:  
                if itype == 1:  
                    if list[2] != 'ipv4':  
                        continue  
                elif itype == 2:  
                    if list[2] != 'ipv6':  
                        continue  
                else:  
                    if list[2] != 'ipv4':  
                        continue  
            else:  
                if list[2] == 'asn':  
                    continue  
            if list[2] == 'ipv6':  
                print '%s/%s' % (list[3],list[4])  
            elif list[2] == 'ipv4':  
                print '%s/%d' % (list[3],32-int(math.log(int(list[4]),2)))  
        fs.close()  

    if __name__ == '__main__':  
        argLen = len(sys.argv)  
        if argLen < 2:  
            _usage()  
            sys.exit(0)  
        arg = sys.argv  
        single1 = 0  
        single2 = 0  
        itype = 1  
        iview = 1  
        for x in range(1,argLen):  
            if arg[x] == '-ipv4':  
                single1 += 1  
                itype = 1  
            if arg[x] == '-ipv6':  
                single1 += 1  
                itype = 2  
            if arg[x] == '-all':  
                single1 += 1  
                itype = 3  
            if arg[x] == '-new':  
                if not getApnicFile():  
                    print '[-] Download new ip file failed!'  
                pass  
            if arg[x] == '-mask':  
                single2 += 1  
                iview = 1  
            if arg[x] == '-part':  
                single2 += 1  
                iview = 2  

        if single1 > 1:  
            print '[-] ipv4,ipv6,all only select one.\n'  
            sys.exit(0)  
        if single2 > 1:  
            print '[-] mask,part only select one.\n'  
            sys.exit(0)  
        if not os.path.exists(local_file):  
            if not getApnicFile():  
                sys.exit(0)  
        location = sys.argv[1].upper()  
        if iview == 2:  
            viewPartInfo(location,itype)  
        else:  
            viewMaskInfo(location,itype)
    ```

如上所示，我们执行脚本后可以得到列表，同时导出即可。

    ```html;
    python china_ip.py cn > r.txt
    ```
