由网络范围计算网络号的python脚步代码
最近老大交待了一个任务要部分网络范围让统计出以掩码形式的网络号,以为就是计算网络号嘛,就爽快的答应了;等拿到文件结果傻眼了,额滴神啊,有9万多条记录...哎,找工具吧..查了半天工具都不支持批量处理...
哎,没办法写代码吧...久违的感觉又来了...
先介绍一下用法吧,首先将ip范围以行的形成统计到execel里,然后导成以逗号(,)分隔的csv文件命名为ip.csv,然后放到脚步的同目录下,执行python network.py即可,打印结果的同时会生成ip.txt文件;
附:
#!/usr/bin/python
#source-file ip.csv(interv with',') yi ge ip fan wei
#dest-file ip.txt
#liuan 20091016
#filename network.py
import os
def to_binary(x) :
result = ''
while x > 0 :
m = x % 2
x = x / 2
result = str(m) + result
return result
def net_js(a,b) :
A = to_binary(a)
result = 0
mask = 0
B = to_binary(b)
if len(A) > len(B) :
length = len(A)
result = 8 - length
elif len(A) < len(B) :
length = len(B)
result = 8 - length
else :
length = len(A)
i = 1
while i < length :
mask = mask + 2**(length-i)*int(A[i-1])
if A[i] != B[i] :
result = 8 - length + i
break
i = i + 1
return result,mask
def print_netmask(a , b) :
A1 = int(a[:a.index('.')])
a = a[a.index('.')+1:]
B1 = int(a[:a.index('.')])
a = a[a.index('.')+1:]
C1 = int(a[:a.index('.')])
a = a[a.index('.')+1:]
D1 = int(a)
A2 = int(b[:b.index('.')])
b = b[b.index('.')+1:]
B2 = int(b[:b.index('.')])
b = b[b.index('.')+1:]
C2 = int(b[:b.index('.')])
b = b[b.index('.')+1:]
D2 = int(b)
netmask = ''
while 1 :
if A1 != A2 :
result ,mask = net_js(A1,A2)
netmask = str(mask)+".0.0.0/" + str(result)
break
else :
if B1 != B2 :
result ,mask = net_js(B1,B2)
netmask = str(A1)+"."+str(mask)+".0.0/"+str(8+result)
break
else :
if C1 != C2 :
result ,mask= net_js(C1,C2)
netmask = str(A1)+"."+str(B1)+"."+str(mask)+".0/"+str(16+result)
break
else :
if D1 != D2 :
result ,mask = net_js(D1,D2)
netmask = str(A1)+"."+str(B1)+"."+str(C1)+"."+str(mask)+"/"+str(24+result)
#netmask = str(A1)+"."+str(B1)+"."+str(C1)+"."+str(256-2**(8-result))+"/"+str(24+result)
break
else :
break
# print "ok"
# print A1, B1, C1 ,D1 ,A2 ,B2 ,C2 ,D2
# f=open("ip.txt","a")
# f.write(a)
# f.write(b)
# f.write("\r")
# f.write(netmask)
# f.close()
os.system("echo %s >> ip.txt" % netmask)
print netmask
if __name__ == "__main__" :
f = open("ip.csv")
list = f.readlines()
# print len(list)
i = 0
while i < len(list) :
line = list[i]
a = line[:line.index(',')].strip()
b = line[line.index(',')+1:].strip()
#print a ,b
#print b
print_netmask(a,b)
i = i+1
f.close()
阅读(1699) | 评论(0) | 转发(0) |