使用python-nmap 搭建基本端口扫描器
字数 967 2025-08-18 11:39:04
Python-nmap 端口扫描器开发指南
概述
本教程将详细介绍如何使用 Python-nmap 库构建一个基本的企业级端口扫描器,用于监控企业内部服务器开放的端口和服务。通过此工具,网络管理员可以及时发现并管理服务器上的开放端口,从而在漏洞出现时快速响应。
开发环境准备
基础环境要求
- Python 2.7(虽然现在推荐使用Python 3.x,但原文基于2.7)
- nmap 网络扫描工具
- python-nmap 库
安装步骤
-
安装nmap工具:
- Linux:
sudo apt-get install nmap - Windows: 从官网下载安装包
- Linux:
-
安装python-nmap库:
pip install python-nmap注意:要安装的是
python-nmap而不是nmap
核心实现原理
基本流程图
- 初始化进程池
- 从IP地址库读取目标主机/网段
- 对每个目标执行nmap扫描
- 解析扫描结果
- 按端口分类存储结果
关键技术点
1. 多进程处理
使用Python的multiprocessing.Pool提高扫描效率:
from multiprocessing import Pool
p = Pool(4) # 根据机器性能设置进程数
2. IP地址库处理
使用文本文件存储IP资源,每行一个IP地址或网段:
hosts = open("ip.txt")
for host in hosts:
print(host.strip()) # 去除换行符
3. nmap扫描核心代码
import nmap
nm = nmap.PortScanner()
ret = nm.scan(
hosts=ip,
ports=config.scan_port_range,
arguments=config.scan_options,
sudo=config.scan_sudo
)
参数说明:
ip: 目标IP或网段scan_port_range: 要扫描的端口范围,如"20-443"scan_options: nmap扫描选项,如"-sS -T4"scan_sudo: 是否使用sudo权限
4. 扫描结果解析
扫描结果结构示例:
{
'scan': {
'192.168.1.1': {
'status': {'state': 'up', 'reason': 'echo-reply'},
'tcp': {
80: {
'state': 'open',
'name': 'http',
'product': 'Apache httpd',
'version': '',
'extrainfo': '',
'conf': '10',
'cpe': 'cpe:/a:apache:http_server'
},
443: {...}
}
}
}
}
结果处理代码:
ret = nm.scan(ip, config.scan_port_range, config.scan_options, config.scan_sudo)
scan_host_count = len(ret['scan'].keys())
if scan_host_count != 0:
for ip, result in ret['scan'].items():
tcp_result = result.get('tcp', {})
for port, detail in tcp_result.items():
if detail.get('state') == 'open':
process_result(ip, port, detail)
5. 结果存储
按端口号分类存储结果:
def process_result(ip, port, detail):
print(f"{ip} {port} {detail}")
# 按端口号创建报告文件
report_file = f"reports/port_{port}"
with open(report_file, "a") as f:
f.write(f"{ip} {port} {detail}\n")
完整示例代码
import nmap
from multiprocessing import Pool
import config # 自定义配置文件
def process_result(ip, port, detail):
"""处理并存储扫描结果"""
print(f"[+] Found open port: {ip}:{port} - {detail.get('name', 'unknown')}")
# 按端口分类存储
report_file = f"reports/port_{port}"
with open(report_file, "a") as f:
f.write(f"{ip}\t{port}\t{detail}\n")
def scan_target(ip):
"""扫描单个目标"""
try:
nm = nmap.PortScanner()
ret = nm.scan(
hosts=ip,
ports=config.scan_port_range,
arguments=config.scan_options,
sudo=config.scan_sudo
)
if 'scan' in ret:
for ip, result in ret['scan'].items():
tcp_result = result.get('tcp', {})
for port, detail in tcp_result.items():
if detail.get('state') == 'open':
process_result(ip, port, detail)
except Exception as e:
print(f"[-] Error scanning {ip}: {str(e)}")
def main():
# 初始化进程池
pool = Pool(config.pool_size)
# 读取IP地址库
with open(config.host_file) as f:
targets = [line.strip() for line in f if line.strip()]
# 并行扫描
pool.map(scan_target, targets)
pool.close()
pool.join()
if __name__ == "__main__":
main()
配置建议
创建config.py文件存放配置:
# 扫描配置
scan_port_range = "20-443" # 扫描端口范围
scan_options = "-sS -T4" # nmap扫描选项
scan_sudo = True # 是否需要sudo权限
# 文件路径
host_file = "ip.txt" # IP地址库文件
pool_size = 4 # 进程池大小
实际应用建议
- 定时扫描:结合cron或计划任务定期执行扫描
- 结果分析:编写脚本分析历史变化,检测异常开放端口
- 告警机制:对关键端口的变化设置告警
- 权限控制:扫描器运行账户应有足够权限但不应是root
- 日志记录:详细记录扫描操作和结果
注意事项
- 仅用于授权扫描,禁止扫描非自己管理的网络
- 控制扫描频率,避免对网络和设备造成过大负载
- 敏感扫描结果应加密存储
- 大规模扫描前先在小范围测试参数
通过本教程,您已经掌握了使用python-nmap构建企业级端口扫描器的核心技术。根据实际需求,您可以进一步扩展功能,如添加Web界面、集成漏洞扫描等。