Python3 实现将ip段分成单个IP

ip格式只支持*.*.*.*/*和*.*.*.*-*格式
使用方法:将你要处理的ip段保存在txt中,将filename改为你保存的txt文件名。
脚本效果:生成IP-range_result.txt文件。

from IPy import IP
import re
import os


def main():
    dic = []
    filename = 'IP-range.txt'       #IP segment filename to be processed
    fo = open(filename,"r")
    for line in fo:
        data = line
        ips = re.search(r'((2[0-4]\d|25[0-5]|[01]{0,1}\d{0,1}\d)\.){3}(2[0-4]\d|25[0-5]|[01]{0,1}\d{0,1}\d)[-/]',line)      #Select the network segment type
        if(ips != None):
            ips = re.search(r'((2[0-4]\d|25[0-5]|[01]{0,1}\d{0,1}\d)\.){3}(2[0-4]\d|25[0-5]|[01]{0,1}\d{0,1}\d)[/]',line)   #Separate/type and -type
            
            #Processing/type
            if(ips != None):
                ip = IP(data)
                for x in ip:
                    dic.append(str(x))
            
            #process-type        
            else:
                ip_1 = line.split('-')[-2].split('.')[-4]
                ip_2 = line.split('-')[-2].split('.')[-3]
                ip_3 = line.split('-')[-2].split('.')[-2]
                ip_4 = line.split('-')[-2].split('.')[-1]
                ip_last = line.split('-')[-1]
                ip_last.strip()
                ip_len = int(ip_last) - int(ip_4) + 1
                for i in range(ip_len):
                    
                    ip_last = int(ip_4) + i
                    ip_result = ip_1 + '.' + ip_2 + '.' + ip_3 + '.' + str(ip_last)
                    dic.append(ip_result)
        else:
            dic.append(data)
            
    fo.close()
    
    #Write the result to a file
    filename_result_1 = 'IP-range_1.txt'
    f1 = open(filename_result_1,"w+")
    for line in dic:
        f1.write(line+'\n')
    f1.close()
    
    
    #Remove empty lines
    filename_result_2 = 'IP-range_result.txt'
    f1 = open(filename_result_1,"r")
    f2 = open(filename_result_2,"w+")
    try:
        for line in f1.readlines():
            if line == '\n':
                line = line.strip("\n")
            f2.write(line)
    finally:
        f1.close()
        f2.close()
            
    
    if os.path.exists(filename_result_1):
        os.remove(filename_result_1)
    
main()

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值