问题描述
我对 python 比较陌生,所以我没有最多的知识。我正在使用 python-nmap 来扫描网络范围,但我最纠结的问题是将结果输出到文本文件。 这是我目前所拥有的
import nmap
ip = '192.168.20.1'
port = 80
nmap = nmap.PortScanner()
result = nmap.scan(ip,str(port))
port_status = (result['scan'][ip]['tcp'][port]['state'])
print(f"Port {port} is {port_status} on {ip}")
with open('nmap.txt','w') as file:
file.write(f"Port {port} is {port_status} on {ip}")
虽然这仅适用于单个 IP,但我尝试扫描整个网络范围,例如 192.168.20.0/24。 当我将 ip 变量设置为“192.168.20.0/24”时,我收到以下错误代码:
Traceback (most recent call last):
File "c:/Users/john/Desktop/Python/Test.py",line 8,in <module>
port_status = (result['scan'][ip]['tcp'][port]['state'])
KeyError: '192.168.20.0/24'
我觉得对此有一个非常简单的解决方法,我的一部分人觉得发布此内容很愚蠢,但非常感谢您的帮助。 谢谢
解决方法
使用 CIDR 表示法,您将获得多个结果,而第 8-11 行只能处理一个结果。您需要一个循环来处理 python-nmap 结果。
import nmap
ips = '192.168.20.0/24'
port = 80
nmap = nmap.PortScanner()
nmap.scan(ips,port)
with open('nmap.txt','w') as file:
for host in nmap.all_hosts():
port_state = nmap[host]['tcp'][port]['state']
print(f"Port {port} is {port_state} on {host}")
file.write(f"Port {port} is {port_state} on {host}")