簡體   English   中英

單個 IP 地址匹配需要正則表達式

[英]Need regular expression for singular IP address match

我試圖根據 IP 地址指定要打印的內容,但 python 抓取 172.16.200.2 並將其與匹配“172.16.200.2XX”的任何內容進行匹配。 這會導致如何處理 172.16.200.2X 的問題

該代碼從 172.16.200.2 - 172.16.200.26 的列表中獲取 IP

我可以做一個“導入重新”,但我不知道如何編寫它以匹配單個 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 以充當簡單的網絡監視器。

如果您嘗試將單個完整 IP 地址與每個 if-else 語句匹配,則可以僅使用==條件。 例如:

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

如果您想將其擴展到更多 IP 地址而不必編寫大量 if-else 語句,您可以使用我們的字典。

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

我希望這有幫助!

不完全確定您在這里追求的是什么,但是使用字典來映射最后兩個八位字節也感覺像是在重復很多工作。 為什么不嘗試這樣的事情:

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將打印200.10 ,和172.16.200.21將打印200.21 ..等在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM