Python3搜索IP列表并在没有匹配的情况下打印“No Matches”。使用ipaddress模块

问题描述 投票:0回答:1

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

我的问题是当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:'是我无法工作的。它打印出“完成扫描”,但就是这样。

python-3.x loops while-loop
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.