2017-06-23 118 views
0

我有我的黑名單IP地址在一個文件中,我的測試IP地址在另一個。如果我的測試IP地址與我黑名單IP文件中的IP匹配。我打印出IP和黑色列出.txt如果被發現。Python3搜索IP列表並打印「無匹配」,如果不匹配。 ipaddress模塊​​使用

我的問題是當IP不匹配。我希望它打印出「NO Matches」一次,但是它會跳過這部分,或者打印出每個沒有匹配的IP。它沒有什麼大不了的,除了它讓我不能理解,它可能非常簡單。

我正在使用ipaddress模塊​​,因爲我還使用子網搜索IP地址。我嘗試過每個我能想到的循環,但我沒有想法。

import os, sys 
import ipaddress 
import re 

IPsToTest = open('IP_We_Want_TO_Scan.txt','r').readlines() 

BadIPFiles = [] 
for i in os.listdir('BadIPAddresses\\'): 
    if i.endswith(".txt"): 
     BadIPFiles.append(str(i)) 

""" Single IP Scanning Function """ 
def CheckSingleIP(): 
    for SingleFileName in BadIPFiles: 
     with open('BadIPAddresses\\' + SingleFileName) as MainTest: 
      REGNetIP = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', MainTest.read()) 
      for n in REGNetIP: 
       for IPs in IPsToTest: 
        IPs = IPs.strip() 
        IPs = ipaddress.ip_address(IPs) 
        n = ipaddress.ip_address(n) 
        """ Print IPs matching black lists """ 
        while True: 
         if IPs == n: 
          print("\nMatched in {0} - IP Address {1}".format(SingleFileName,IPs)) 
          break 
         else: 
          if IPs is not n: 
           break 
          print("[+] Great! No Matches! [+]") 
         break 

CheckSingleIP() 
print("\n\n - - - - - - Finished Scanning - - - - - - !\n") 

'else:'是我無法工作的。它確實打印出「完成的掃描」,但就是這樣。

回答

0

您可以在循環的開始處創建一個名爲「MatchFound」的布爾變量,將其設置爲False。如果找到匹配項,請將其設置爲True。 然後在循環結束時運行布爾檢查,如果設置爲True,則打印出您的「[+] Great!No Matches![+]」。