You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何匹配IP与对应端口信息并合并生成指定格式的结果文件?

合并IP列表与端口扫描结果的实现方法

方法一:Bash 循环 + Grep(简单直观)

适合处理小规模的IP列表和端口文件,逻辑清晰易懂:

#!/bin/bash

first_ip=1

while read -r ip; do
    [ "$first_ip" -ne 1 ] && echo ""
    echo "$ip"
    grep -A1 "on IP: $ip" Ports.txt
    first_ip=0
done < IP.txt > Results.txt

代码说明:

  • while read -r ip 逐行读取IP.txt中的每个IP地址
  • [ "$first_ip" -ne 1 ] && echo "" 除第一个IP外,每个IP块前输出空行做分隔
  • grep -A1 "on IP: $ip" Ports.txt 匹配包含目标IP的端口行,并额外输出该行的下一行(即banner内容)
  • 所有结果直接写入Results.txt

方法二:Awk 脚本(高效处理大文件)

当IP数量或端口记录较多时,Awk的单进程处理比多次调用Grep效率更高:

#!/usr/bin/awk -f

BEGIN {
    while ((getline ip < "IP.txt") > 0) {
        ip_list[ip] = 1
    }
    close("IP.txt")
    first_block = 1
}

{
    if ($0 ~ /on IP: ([0-9]+\.){3}[0-9]+/) {
        match($0, /on IP: (([0-9]+\.){3}[0-9]+)/, ip_match)
        current_ip = ip_match[1]
        if (current_ip in ip_list) {
            target_ip = current_ip
            if (!first_block) print ""
            first_block = 0
            if (!printed_ip[target_ip]) {
                print target_ip
                printed_ip[target_ip] = 1
            }
            print $0
        } else {
            target_ip = ""
        }
    } else if (target_ip != "") {
        print $0
    }
}

使用方式:

  1. 将上述代码保存为merge.awk
  2. 执行命令:awk -f merge.awk Ports.txt > Results.txt

代码说明:

  • BEGIN块:先读取IP.txt的所有IP存入数组,后续用来校验是否是需要处理的IP
  • 遍历Ports.txt的每一行:
    • 匹配包含IP的端口行,提取出IP并检查是否在目标列表中
    • 首次处理目标IP时先输出IP地址,然后输出端口行和对应的banner行
    • 不同IP块之间自动插入空行分隔

内容的提问来源于stack exchange,提问作者Robot110010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:30:50