python 根据ip与mask计算ip地址范围的代码

发布时间:2020-12-25编辑:脚本学堂
本文介绍下,根据IP与mask信息计算出IP地址范围的python代码一例,有需要的朋友,可以参考学习下。

代码如下:

复制代码 代码示例:
#!/usr/bin/python
#source-file ip.cfg,for example ip/mask
#dest-file  ip.txt
#liuan 20120730
#filename network.py
import os
import sys
def to_binary(x) :
    result = ''
    x=int(x)
    while x > 0 :
        m = x % 2
        x = x / 2
        result = str(m) + result
    i=0
    pre_str=""
    while i < 8-len(result):
        pre_str= pre_str + "0"
        i = i + 1
    #print pre_str+result
    return pre_str + result
def net_js(str,length) :
    i=0
    net=0
    while i < length:
        if str[i] == "1":
            net=net + pow(2,8-i-1)
        i = i +1
    return net
def print_netmask(net, mask,domain_id,device_id) :
    net=net.split('.')
    A = net[0].strip()
    B = net[1].strip()
    C = net[2].strip()
    D = net[3].strip()
    m=mask/8
    n=mask%8
    if m==0 :
        network=net_js(to_binary(A),n)
        ip_min=str(network)+".0.0.0"
        ip_max=str(network+pow(2,8-n)-1) + ".255.255.255"
    elif m==1:
        network=net_js(to_binary(B),n)
        ip_min=A + "." +  str(network) + ".0.0"
        ip_max=A + "." +  str(network+pow(2,8-n)-1) + ".255.255"
    elif m==2:
        network=net_js(to_binary(C),n)
        ip_min=A + "." + B + "." + str(network) + ".0"
        ip_max=A + "." + B + "." + str(network+pow(2,8-n)-1) + ".255"
    elif m==3:
        network=net_js(to_binary(D),n)
        ip_min=A + "." + B + "." + C + "." + str(network)
        ip_max=A + "." + B + "." + C + "." + str(network + pow(2,8-n)-1)
    elif m==4:
        network=net_js(to_binary(D),n)
        ip_min=A + "." + B + "." + C + "." + D
        ip_max=A + "." + B + "." + C + "." + D
    else:
        pass
    result="insert into ppmservice values(" + str(device_id) +"," + domain_id + ",'" + ip_min + "','" + ip_max + "');"
    print result
    if not os.path.isfile("./ip.txt"):
        os.system("touch ip.txt")
    os.system("echo "" + result + "" >> ./ip.txt")
if __name__ == "__main__" :
    if len(sys.argv) !=3 :
        print "please input options 'domain_id' & 'start device_id'"
        sys.exit()
    domain_id=sys.argv[1]
    device_id=int(sys.argv[2])
    if not os.path.isfile("./ip.cfg"):
        print "It is not found file 'ip.cfg',please check ..."
        sys.exit()
    f = open("ip.cfg")
    list = f.readlines()
    i = 0
    while i < len(list) :
        line = list[i].split('/')
        net=line[0].strip()
        mask=int(line[1].strip())
        print_netmask(net,mask,domain_id,device_id+i)
        i = i+1
    f.close()