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