简体   繁体   中英

Need regular expression for singular IP address match

Im trying to specify what to print based on IP addresses but python grabs 172.16.200.2 and matches that to anything matching "172.16.200.2XX". This causes a problem for what to do for 172.16.200.2X

The code grabs ip's from a list ranging 172.16.200.2 - 172.16.200.26

I could do an "import re" but im not sure how to write it to match a singular 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

The output should print 200.2 for 172.16.200.2 and 200.21 for 172.16.200.21 and not 200.2 for any thing ending in 200.2

Ideally im going to use the code to light up some neopixel LED's to act as a simple network monitor.

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!

Not entirely sure what you are after here, but using a dictionary to map the last two octets also feels like you are duplicating a lot of effort. Why not try something like this:

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

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

This will print the third and forth octets if the third is 200, and the final octet is in the specified range (eg 172.16.200.2 will print 200.2 , 172.16.200.10 will print 200.10 , and 172.16.200.21 will print 200.21 .. and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM