Neurohazard
暮雲煙月,皓首窮經;森羅萬象,如是我聞。

将 CIDR 转换为 IP Range 的脚本

wpadmin~June 4, 2019 /Software Engineering

将 CIDR 转换为 IP Range 的脚本

正文

import socket
import struct
from netaddr import *


def findIPs(start, end):
    ipstruct = struct.Struct('>I')
    start, = ipstruct.unpack(socket.inet_aton(start))
    end, = ipstruct.unpack(socket.inet_aton(end))
    return [socket.inet_ntoa(ipstruct.pack(i)) for i in range(start, end+1)]

FILE1 = 'ip.txt'
FILE2 = 'iplist.txt'

f1 = open(FILE1, "r")
line1=f1.readlines()
f3 = open(FILE2,"w+")

for m in line1:
    if '-' in m:
       Str1 = m.split('.')
       Str2 = Str1[3].split('-')
       Str3 = Str1[0] + '.' + Str1[1] + '.' + Str1[2] + '.' + Str2[0]
       Str4 = Str1[0] + '.' + Str1[1] + '.' + Str1[2] + '.' + Str2[1]
       ip_list = findIPs(Str3, Str4)
       for x in ip_list:

          f3.read()
          f3.write(str(x)+"\n")
    else :
       ip = IPNetwork(m)
       for x in ip:
         f3.read()
         f3.write(str(x) + "\n")

f1.close()
f3.close()
f4 = open(FILE2,"r")
line2=f4.readlines()
f5 = open(FILE2,"w+")

line3= list(set(line2))
line3.sort(key=line2.index)

for i  in line3:
    f5.write(str(i))

f4.close()
f5.close()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.