Python3搜索IP列表并打印" No Matches"如果没有匹配。使用ipaddress模块

时间:2017-06-23 00:36:41

标签: python-3.x loops while-loop

我将黑名单中的IP地址放在一个文件中,将我的测试IP地址放在另一个文件中。如果我的测试IP地址与我列入黑名单的IP文件中的IP匹配。我打印出IP和黑名单.txt如果在。中找到。

我的问题是IP何时不匹配。我希望打印出来#34; 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")

'否则:'是我无法工作的。它打印出"完成扫描"但那就是它。

1 个答案:

答案 0 :(得分:0)

你可以在循环开始时创建一个名为'MatchFound'的布尔变量,设置为False。如果找到匹配项,请将其设置为True。 然后在循环结束时,检查布尔值,如果设置为True,则打印“[+] Great!No Matches![+]”。