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

Python code getting stuck while trying to handle an exception

代码:

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无法识别版本[时会出现异常=42=] 运行 在主机中。 (这是一个 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 的输出没有任何问题,我又犯了一个巨大的初学者错误,这就是我的代码卡住的原因..

备注:

让你厌倦了以上所有内容,有没有人知道一种方法来处理该异常而不会卡住代码?

您忘记在 运行 try-except 块中的代码中添加异常类型以进行排除。

这应该可以解决问题:

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