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

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

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)

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

python china_ip.py cn > r.txt
相关推荐:
pip类似RedHat里面的yum,安装Python包非常方便。 python -m pip install --upgrade pip
如何让一个Python脚本输出的文字信息是彩色的?其实这个其实跟python无关的,跟具体所用console的类型有关系,不同的类型对应不同的控制码,如果是ansi终端,可以用ansi的控制码。 Mac或Linux终端中的颜色 …
有的网站需要登陆才能抓取到网站的数据,那么光模拟浏览器请求网站内容是还不够了,还需要能够模拟用户登陆网站,然后保留登陆状态,获取网站相关的内容。 想要成功模拟真实用户登陆,重点要找到登录时候提 …
原因在于系统里有多个版本冲突所导致的。 使用以下的命令代替: python -m pip
有时候我们想要用不同色彩的文字来区分下,但是在Windows上不同于Mac或Linux,无法使用\033的方法,那怎么办呢?这里我们将对Windows下命令行输出彩色文字进行分析。 首先我们来看一段代码,品味下是怎么生 …
拿起手机扫一扫即可带走我!