需要用于单个IP地址匹配的正则表达式

时间:2019-01-15 18:03:56

标签: python python-3.x

我试图根据IP地址指定要打印的内容,但是python抓取172.16.200.2并将其与匹配“ 172.16.200.2XX”的任何内容匹配。这会导致172.16.200.2X该怎么办

代码从范围为172.16.200.2-172.16.200.26的列表中获取IP

我可以做一个“ import re”,但是我不确定如何写它来匹配单个IP

with open('iplist.txt', 'r') as f:
    for ip in f:
        ip = ip.strip()
        result = subprocess.Popen(["ping", '-n', '2', ip],stdout=f, stderr=f).wait()
        if result:
            print (bcolors.FAIL + ip, "inactive")
        else:
            print (bcolors.OKGREEN + ip, "active")
            if "1.1.1.1" in ip:
                print ("cloudflare!")
            elif "172.16.200.2" in ip:
                print ("200.2")
            elif "172.16.200.21" in ip:
                print ("200.21")
            else:
                pass

对于172.16.200.2,输出应打印200.2,对于172.16.200.21,应打印200.21,对于以200.2结尾的任何内容,则不应输出200.2

理想情况下,我将使用该代码点亮一些新像素LED来充当简单的网络监视器。

2 个答案:

答案 0 :(得分:0)

If your trying to match a single, entire IP address with each if-else statement, you could just use the == conditional. For example:

if "172.16.200.2" == ip:
    print ("200.2")
## etc..

If you want to scale this to many more IP addresses without having to write tons of if-else statements, you could us a dictionary.

ip_dict = {
    "1.1.1.1": "cloudflare!",
    "172.16.200.2": "200.2",
    "172.16.200.21": "200.21",
    "192.168.0.1": "0.1",
    "etc...": "etc..."
}

## use a try-except block here just in case the ip address is not in your dictionary - avoid error and pass
try:
    print (ip_dict[ip])
except:
    pass

I hope this helps!

答案 1 :(得分:0)

不能完全确定您在这里要做什么,但是使用字典映射最后两个八位字节也感觉就像您在重复很多工作。为什么不尝试这样的事情:

ip_slice = ip.split('.')[2:]

if ip_slice[0] == '200' and ip_slice[1] in range(2,22):
    print('.'.join(ip_slice))

如果第三个八位字节为200,则将打印第三个和第四个八位字节,并且最后一个八位字节在指定范围内(例如172.16.200.2将打印200.2172.16.200.10将打印{{ 1}}和200.10将打印172.16.200.21 ..依此类推。