python根据ip范围批量计算子网掩码


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/python
# -*- coding=utf-8 -*-
# author : kernelsky
# date: 2018-06-21
# version: 0.1

import netaddr
from netaddr import *
import sys

output = sys.stdout
outputfile = open("iplist_mask.txt",'w')
sys.stdout = outputfile
f2 = open("ip_sub.txt","r")
lines = f2.readlines()
for line3 in lines:
    ipNetList = netaddr.iprange_to_cidrs(line3.split( )[1], line3.split( )[2])
    ip_list = []
    for i in ipNetList:
        ip_list.append(str(i).split("/")[0]+"/"+str(i.netmask))
    print str(line3.split( )[0])+"-"+str(ip_list)
outputfile.close()
sys.stdout = output

ip_sub.txt文件格式:
1 103.247.176.1 103.247.179.255
2 219.141.236.1 219.141.236.255
3 210.82.53.128 210.82.53.131
4 202.204.224.155 202.204.224.159
5 12.191.8.190 12.191.8.190
6 218.205.220.0 218.205.220.255
7 114.242.14.148 114.242.14.148
8 12.191.8.167 12.191.8.167
9 218.205.215.0 218.205.215.255
10 210.72.16.32 210.72.16.63
11 124.205.205.0 124.205.206.127
12 106.120.124.0 106.120.126.255
13 222.29.0.0 222.29.159.255
14 194.90.239.129 194.90.239.129
15 202.112.7.0 202.112.8.255
最终转换效果:


Whatever is worth doing is worth doing well.