Nmap批量测试IP存活性及输出脚本

Hexa 记录 发布于 6 天前 8 次阅读


平时需要批量跑IP存活性或者端口连通性,比起现写脚本,情况允许的话还是选择性能和功能都更强大的nmap来测试

Nmap批量测试

先把要测试的IP一行一个保存在ip.txt中,再使用以下命令,如果需要测试ipv6,在nmap后面加上-6,端口可改为自己要测的,也可以根据需求使用其他的参数去测试不同协议

nmap -Pn -p80,443 --open -T4 -iL ip.txt -oN result.txt

提取数据

这块写了一个python脚本用来提取数据到表格

import re

input_file = "result.txt"   # 原始Nmap输出
output_file = "nmap_parsed.csv"  # 输出CSV文件

with open(input_file, "r", encoding="utf-8") as f:
    content = f.read()

# 按“每个主机”分组
reports = content.split("Nmap scan report for ")[1:]

results = []

for report in reports:
    lines = report.strip().splitlines()
    ip = lines[0].strip()

    for line in lines:
        # 端口行如:80/tcp  open  http
        match = re.match(r"(\d+/tcp)\s+(\w+)\s+(\w+)", line)
        if match:
            port, state, service = match.groups()
            results.append((ip, port, state, service))

# 写入CSV
with open(output_file, "w", encoding="utf-8") as f:
    f.write("IP,Port,State,Service\n")
    for row in results:
        f.write(",".join(row) + "\n")

print(f"[+] 已提取 {len(results)} 条记录到 {output_file}")

还可以用下面这个脚本再从表格中提取到IP:端口格式的数据

import csv

input_csv = "nmap_parsed.csv"
output_txt = "res.txt"

with open(input_csv, newline='', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    ip_ports = []

    for row in reader:
        ip = row['IP']
        port = row['Port'].split('/')[0]  # 提取端口号(去掉 /tcp)
        ip_ports.append(f"{ip}:{port}")

# 去重并排序(可选)
ip_ports = sorted(set(ip_ports))

with open(output_txt, "w", encoding="utf-8") as f:
    for entry in ip_ports:
        f.write(entry + "\n")

print(f"[+] 提取完成,写入 {output_txt}")

本站站长,热爱倒腾的it爱好者一枚~
最后更新于 2025-06-19