将IP范围扩展到列表

时间:2019-06-02 12:23:16

标签: python list

我有以下代码,我想做的是创建一个小函数,以便在输入IP范围(其中包含:)时将所有范围附加到列表中。

collected_ips = []
while True:
    query = input("IP:\t")
    if not query:
        break
    elif len(query.split('.'))==4:
        temp = query.split('.')
        #result1 = all([i.isdigit() for i in t]) #must be True
        if query.find(":")==-1:
            try:
                result2 = all([0<=int(i)<=255 for i in temp])
                if result2:
                    collected_ips.append(query)
            except ValueError:
                print("Please Fix Input")
        elif len(x.split(":"))==2:
            #function here
            #append to collected_ips
        else:
            print("Please Fix Input")
    else:
        print("Please Fix Input")

输入示例:

123.123.30.20:50

输出:

['123.123.30.20,'123.123.30.21'...'123.123.30.50']

输入示例:

123.123.20:50.30

输出:

['123.123.20.30','123.123.21.30',...'123.123.50.30']

2 个答案:

答案 0 :(得分:1)

这是使用range生成两个范围之间的数字的一种方法:

def spread_ip_range(ip):
    splits = ip.split('.')
    indx = next((i for i, x in enumerate(splits) if ':' in x), -1)

    lst = []

    if indx != -1:
        _from, to = splits[indx].split(':')
        ranges = range(max(0, int(_from)), min(255, int(to)) + 1))

        for r in ranges:
            s = '.'.join(splits[:indx]) + '.' + str(r)
            if splits[indx+1:]:
                s += '.' + '.'.join(splits[indx+1:])
            lst.append(s)
    return lst

用法

>>> spread_ip_range('123.123.20:50.30')
['123.123.20.30', '123.123.21.30', '123.123.22.30', ......, '123.123.49.30', '123.123.50.30']

-

>>> spread_ip_range('123.123.30.20:50')
['123.123.30.20', '123.123.30.21', '123.123.30.22', ......, '123.123.30.49', '123.123.30.50']

答案 1 :(得分:1)

您还可以使用reduce(来自functools)更简洁地做到这一点:

from functools import reduce
def expandIp(ip):
  nodes  = [list(map(int,n.split(":"))) for n in ip.split(".")]
  ranges = [range(max(n[0],0),min(n[-1]+1,256)) for n in nodes]
  ips    = reduce(lambda a,rng: [ip+[n] for ip in a for n in rng],ranges,[[]])
  return [".".join(str(n) for n in ip) for ip in ips]
  • nodes将ip模式转换为[开始]或[开始,结束]范围值的列表
  • ranges在没有“:”说明符的节点(也将节点的范围限制在0 ... 255范围内)时,使用起始编号作为结尾将节点转换为实际范围。
  • ips将每个节点范围与先前节点的所有值组合在一起
  • 结果是将每个组合中的节点与“。”串联。作为分隔符

注意:此解决方案将适用于ip参数中的多个范围说明符。例如expandIp("10.1.1:2.100:101")将产生:10.1.1.100、10.1.1.101、10.1.2.100、10.1.2.101。因此,如果您打算将其用于子网,则可以执行expandIp("10.0.1:3.0:255")

顺便说一句,您可以在函数开始时或在调用它之前用单个条件验证ip参数(这样,您就不必使用min / max来分配{{1} }变量):

ranges

最终功能如下:

n0255 = { str(n) for n in range(256) }  
if not all( i<4 and j<2 and r in n0255 for i,n in enumerate(ip.split(".")) for j,r in enumerate(n.split(":"))):
    print("Invalid Input")

这将简化您的调用代码:

from functools import reduce
n0255 = { str(n) for n in range(256) }  
def expandIp(ip):
  if not all( i<4 and j<2 and r in n0255 for i,n in enumerate(ip.split(".")) for j,r in enumerate(n.split(":"))):
      return None
  nodes  = [list(map(int,n.split(":"))) for n in ip.split(".")]
  ranges = [range(n[0],n[-1]+1) for n in nodes]
  ips    = reduce(lambda a,rng: [ip+[n] for ip in a for n in rng],ranges,[[]])
  return [".".join(str(n) for n in ip) for ip in ips]