基于len of list / array

时间:2017-04-25 22:18:21

标签: python arrays python-2.7 list

我正在尝试编写一个在Cisco路由器上运行命令并在文本文件上写入IP列表的程序。我能够将所有IP写入文件,然后成功获取所有IP。现在,我遇到麻烦的部分是我不知道我将从列表中获得多少IP。因为我想比较我从文件中获取的每个IP与用户定义的IP,我想要一种方法来创建基于IP的动态变量,或者以某种方式迭代所有IP并将其与用户的IP进行比较。

import re
import ipaddr

userIP = raw_input('Enter IP address to compare i.e, 10.10.10.0/24:')
ipFile = ("router.com.txt")
found = []
with open(ipFile, 'r') as f:
    for text in f.readlines()[1:]: #File had a blank line so this skips it
        text = text.rstrip()
        regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})', text)
        #print regex
        found.append(regex)
    print found
    print len(found) - 1

这是我运行时得到的结果:

[['10.10.20.192/27'], ['10.10.40.0/24'], []]
2

现在我正在努力的困难部分是如何动态地将这些与变量 userIP 进行比较。

#if userIP.overlaps(found):
#print "Overlapping IPs!!"
#else:
#print "Does not Overlap!!" 

由于 戴蒙

3 个答案:

答案 0 :(得分:2)

您可以像这样逐个比较每个IP地址和用户输入子网(实际上它使用的内存比代码少):

import re

userIP = raw_input('Enter IP address to compare i.e, 10.10.10.0/24:')
userIP = pseudoSubnetClass(userIP)     # pseudo code
ipFile = ("router.com.txt")
found = []
with open(ipFile, 'r') as f:
    for text in f: #File had a blank line so this skips it
        text = text.rstrip()
        match = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})', text)
        if not match:
            continue
        found = match[0]
        if userIP.overlaps(found):     # This part is
            print "Overlapping IPs!!"  # pseudo code too
            break
    else:
        print "Does not Overlap!!"

答案 1 :(得分:1)

我认为,一旦考虑到re.findall会在文件本身的所有行上提取所有IP,你就不需要拥有自己的循环,就可以避免很多复杂性。例如:

import re

userIP = raw_input('Enter IP address to compare i.e, 10.10.10.0/24:')
ipFile = "router.com.txt"

with open(ipFile) as f:
    for ip in re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})', f.read()):
        if overlaps(ip, userIP):
            print "Overlapping IPs!!"
            break

overlaps()函数只是一个组成的例子,以帮助说明逻辑的其余部分。

答案 2 :(得分:0)

这可能是你想要的吗?

append更改为extend,以便结果列表类似于['10.10.20.192/27', '10.10.40.0/24', '']

found.extend(regex)

询问userIP是否与找到的任何一个匹配:

if userIP in found:
    <suite>