【问题标题】:Python3 Search an IP list and print "No Matches" if no matches. ipaddress module usedPython3 搜索一个 IP 列表,如果没有匹配则打印“No Matches”。使用的ipaddress模块
【发布时间】:2017-11-26 10:29:10
【问题描述】:

我的黑名单 IP 地址在一个文件中,而我的测试 IP 地址在另一个文件中。如果我的测试 IP 地址与我的黑名单 IP 文件中的 IP 匹配。它会打印出 IP 以及如果在其中找到的黑名单 .txt。

我的问题是 IP 不匹配时。我希望它打印一次“不匹配”,但它会跳过这部分或为每个不匹配的 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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2014-10-04
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多