0

代码:

def ScanNetwork():
        nmScan = nmap.PortScanner()
        s = nmScan.scan("192.168.1.1/24", '0-4444', arguments="-O")
            
        for host in nmScan.all_hosts():
            if nmScan[host].state() == "up":
                print("Host : %s (%s)" % (host, nmScan[host].hostname()))
                try:
                    print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
                except:
                    print("An Error occured while scanning this host!\nNo extra info was collected!")
                    continue
                for proto in nmScan[host].all_protocols():
                    print("---------------------------")
                    print("\nProtocol : %s" % proto)
                    lport = nmScan[host][proto].keys()
                    lport = sorted(lport)
                    for port in lport:
                        print("\nport: " + f'{port}' + "\tstate: " + nmScan[host][proto][port]['state'])
                print("---------------------------\n")  
        print("\n\nScan Completed!")
ScanNetwork()

当nmap无法识别主机中运行的版本或操作系统时,有时会发生异常。(这是一个例外)KeyError

应该处理该异常的部分是:

try:
   print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
    print("An Error occured while scanning this host!\nNo extra info was collected!")
    continue

我当然认为 nmap 的输出没有问题,我又犯了一个巨大的初学者错误,这就是我的代码卡住的原因。

笔记:

  • 我已经让脚本运行了一夜,因为它返回了一些有用的信息,但什么也没发生!
  • 请不要告诉我我需要停止使用该nmap模块并转向nmap3

以上所有内容让您感到厌烦,有没有人知道如何在不卡住代码的情况下仍然处理该异常?

4

1 回答 1

2

在 try-except 块内运行代码时,您忘记将异常类型添加到 excpect。

这应该解决它:

try:
   print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\n" + "Type: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except KeyError:
    print("An Error occured while scanning this host!\nNo extra info was collected!")
    continue

如果您想捕获任何可能发生的异常(包括自定义异常),那么您应该使用以下代码:

try:
   <some critical code with possible exceptions to catch>
except Exception:
   print("An exception occured")

于 2021-04-28T12:39:13.353 回答