使用 bash 解析 Nmap 以显示每个服务后跟每个 ip

Parsing Nmap to display each service followed by each ip using bash

我需要能够显示哪些 ips 打开了每个服务端口,每个服务按字母顺序列出,格式如下:

ftp
============
192.168.33.226
192.168.33.129
192.168.33.220

http-alt
============
192.168.33.243
192.168.33.252

我有一个包含 ip 列表的 nmap 结果的文件,如下所示:

Nmap scan report for 192.168.33.252
Host is up (0.041s latency).
Not shown: 999 filtered ports
PORT     STATE SERVICE
8000/tcp open  http-alt
MAC Address: 00:50:56:AF:1E:5B (VMware)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 2.6.34 (93%), Linux 2.6.18 (CentOS 5, x86_64, SMP) (91%), Linux 2.6.27 (91%), OpenWrt White Russian 0.9 (Linux 2.4.30) (91%), IBM System Storage DS4700 NAS device (91%), Lantronix SLC 8 terminal server (Linux 2.6) (91%), Linux 2.6.21 (91%), Linux 2.6.27 (Ubuntu 8.10) (91%), Linux 2.6.27 - 2.6.28 (91%), Linux 2.6.5 (SUSE Enterprise Server 9) (91%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 1 hop

Nmap scan report for 192.168.33.226
Host is up (0.041s latency).
Not shown: 998 filtered ports
PORT     STATE SERVICE
21/tcp   open  ftp
3389/tcp open  ms-wbt-server
MAC Address: 00:50:56:AF:4E:1D (VMware)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running (JUST GUESSING): Microsoft Windows 2000|2003|2008|XP (94%)
OS CPE: cpe:/o:microsoft:windows_2000::sp4 cpe:/o:microsoft:windows_server_2003::sp1 cpe:/o:microsoft:windows_server_2003::sp2 cpe:/o:microsoft:windows_server_2008::sp2 cpe:/o:microsoft:windows_xp::sp3
Aggressive OS guesses: Microsoft Windows 2000 SP4 (94%), Microsoft Windows Server 2003 SP1 or SP2 (91%), Microsoft Windows Server 2003 SP2 (91%), Microsoft Windows Server 2008 Enterprise SP2 (90%), Microsoft Windows 2003 SP2 (89%), Microsoft Windows XP SP3 (88%), Microsoft Windows 2000 SP0 (85%), Microsoft Windows XP (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 1 hop

我使用 grep 和 awk 设法将文件中的无关信息删除到每个 ip 后跟服务 运行,但不知道从这里去哪里。

cat /usr/share/cctc/NMAP_all_hosts.txt | grep -E "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b|\b+\/tcp\s*open" | awk '{print $NF}' 

给我以下格式:

192.168.33.249
ftp
ssh
192.168.33.236
ssh
ident
netbios-ssn
microsoft-ds

Perl 最初是为了改进 sed/grep/awk 的高级语言特性而编写的。

可能的 Perl 单行代码:

perl -lne '$ip= if /((\d+\.){3}\d+)$/; push @{$h{}}, $ip if /tcp\s+open\s+(.+)$/; END { for (sort keys %h) { print"$_\n========"; print for @{$h{$_}}; print"" } }' nmap.txt

解释:

选项:-l IO 上自动换行 remove/add,-n 将您的代码放入 while (<>) { ... } 循环,-e 表示以下脚本。

不需要来自 cat 的管道,只需添加文件作为最后一个参数。与您的 grep 相同。

在散列 %h 中收集数据,通过服务名称、IP 值数组寻址。

</code> 在正则表达式匹配的括号中包含第一个捕获组。</p> <p>在与 IP 地址匹配的行上更新全局变量 <code>$ip

如果遇到服务名称,将当前 $ip 推送到 %h 哈希服务键下的数组。

END块在隐式循环后运行,进行打印。