IP合并小工具-Python版本


=Start=

缘由:

最近的工作中涉及到一些IP属性分析的内容,在最后分析整理的差不多了之后,需要将对应的IP或IP段合并再展开成单个IP的形式,方便给其它系统/工具使用。这次是用Python写的,主要是借助netaddr模块的功能来实现IP段的合并,后续抽时间看能不能用Golang实现一版,也学习积累一下Golang的编程经验。

正文:

参考解答:

在当前目录下放置一个名为【IP-company.txt】的文件,文件格式如下:

# company_name
ip1 - ip2
ip3
ip4/28

# company_name2
ipX - ipY
ip11

然后执行该脚本,会在当前目录下生成名为【ip_company.txt】的结果文件,文件格式如下:

ip1,company_name,20201022

#!/usr/bin/env python3
# coding=utf-8
import sys, time
from netaddr import *

def ip_format(ip_str):
    var_list = []
    for item in ip_str.strip().split('.'):
        var_list.append(str(int(item)))
    return '.'.join(var_list)

def main():
    company_ip_map = {}
    company_str = ''
    ipset = IPSet()
    with open('IP-company.txt') as fp:
        for line in fp:
            line = line.strip()
            if line:
                if line.startswith('#') and len(line) > 1:
                    company_str = line[1:].lower().strip()
                    ipset.clear()
                    continue
                else:
                    if ' - ' in line:
                        ip_start, ip_end = line.split(' - ', 1)
                        ipset.add(IPRange(ip_format(ip_start), ip_format(ip_end)))
                    else:
                        ipset.add(line)
                    #
                    if company_str in company_ip_map:
                        company_ip_map[company_str] = company_ip_map[company_str] | ipset
                    else:
                        company_ip_map[company_str] = ipset
                    #
                #
            else:
                continue
            #
        #
    #
    for item in company_ip_map:
        print(item, company_ip_map[item].size)
    #
    with open('ip_company.txt', 'w') as fw:
        for item in company_ip_map:
            print(item, company_ip_map[item].size)
            astr = '\n'.join('{0},{1},20201022'.format(str(e), item) for e in company_ip_map[item])
            fw.write( astr )
            fw.write('\n')
    #
#


if __name__ == '__main__':
    time_start = time.time()
    try:
        main()
    except KeyboardInterrupt:
        print('Killed by user')
        sys.exit(0)
    print("\nSpend {0} seconds.\n".format(time.time() - time_start))

参考链接:

Python的netaddr模块使用记录
https://ixyzero.com/blog/archives/2707.html

阿里云IP段的整理
https://ixyzero.com/blog/archives/4961.html

=END=

, ,

发表回复

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