Python 代码在尝试处理异常时卡住

问题描述

代码

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 无法识别 VersionOs 在主机中运行时会发生异常. (这是一个 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

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

解决方法

在 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")