python 对ip段处理
<div id="cnblogs_post_body">需求: ip段 20.20.20.20-20.21.11.11 插入数据库-------------------------------------------------------
写下来供以后重用或有需要的同行~
<div class="cnblogs_Highlighter">#生成下一次循环的边界条件def get_side(pos,now): global begin,end global first,last # find_side # #---------in--------------- #begin 110.67.1.95 end 111.67.1.95 #first 110.x.x.x last 111.x.x.x #pos 110 now 0 #---------out-------------- #first 110.67.x.xlast 111.255.x.x # # find_side = lambda begin, end, pos, fisrt, last, now:\ ( pos == first and begin or 1, pos == last and end or 255) first,last = find_side(begin,end,pos,first,last,now) return range(first,last + 1)def gen_ip(ip): ''' in in 110.67.1.30-110.67.1.32 out '{"110.67.1.30", "110.67.1.31", "110.67.1.33"}' ''' #ip段范围 global begin, end #临时列表,存储边界条件 global first, last sides = ip.split('-') begin = map(lambda x:int(x),sides.split('.')) end = map(lambda x:int(x),sides.split('.')) first = begin last = end ip_str = "'{%s}'" tmp = "" for pos_one in range(begin,end + 1): for pos_two in get_side(pos_one,0): for pos_three in get_side(pos_two,1): for pos_four in get_side(pos_three,2): str = '"%d.%d.%d.%d",' % (pos_one, pos_two, pos_three, pos_four) tmp += str return ip_str % tmp.rstrip(',')
页:
[1]