使用 SED 对 gnmap 字段进行模式匹配

使用 SED 对 gnmap 字段进行模式匹配

我正在测试使用 Splunk 为 nmap 创建字段提取所需的正则表达式,我想我可能接近了......

整行示例:

Host: 10.0.0.1 (host)   Ports: 21/open|filtered/tcp//ftp///, 22/open/tcp//ssh//OpenSSH 5.9p1 Debian 5ubuntu1 (protocol 2.0)/, 23/closed/tcp//telnet///, 80/open/tcp//http//Apache httpd 2.2.22 ((Ubuntu))/,  10000/closed/tcp//snet-sensor-mgmt///  OS: Linux 2.6.32 - 3.2  Seq Index: 257  IP ID Seq: All zeros

我使用下划线“_”作为分隔符,因为它使其更易于阅读。

root@host:/# sed -n -e 's_\([0-9]\{1,5\}\/[^/]*\/[^/]*\/\/[^/]*\/\/[^/]*\/.\)_\n\1_pg' filename

删除转义字符的相同正则表达式:

root@host:/# sed -n -e 's_\([0-9]\{1,5\}/[^/]*/[^/]*//[^/]*//[^/]*/.\)_\n\1_pg' filename

输出:

... ... ...
Host: 10.0.0.1 (host)   Ports: 
21/open|filtered/tcp//ftp///, 
22/open/tcp//ssh//OpenSSH 2.0p1 Debian 2ubuntu1 (protocol 2.0)/, 
23/closed/tcp//telnet///, 
80/open/tcp//http//Apache httpd 5.4.32 ((Ubuntu))/, 
10000/closed/tcp//snet-sensor-mgmt///   OS: Linux 9.8.76 - 7.3  Seq Index: 257 IPID Seq: All zeros
... ... ...

正如您所看到的,模式匹配似乎有效 - 尽管我无法做到:

1 - 在行尾(逗号和空格/制表符)处匹配模式。最后一行包含不需要的文本(在本例中为操作系统和 TCP 计时信息)。两个字符(逗号和空格)的布尔值“OR”似乎不匹配。

...(\,|\s)

2 - 删除任何不必要的数据 - 即仅打印匹配的模式。它实际上是打印整行。如果我删除 sed -n 标志,则其余文件内容也会被打印。我似乎找不到只打印匹配的正则表达式的方法。

即为什么当我明确告诉它不要打印这些行时, sed 却打印这些行?=>

Host: 10.0.0.1 (host) Ports:

OS: Linux 2.6.32 - 3.2  Seq Index: 257  IP ID Seq: All zeros

我对 sed 和 regex 还不熟悉,所以非常感谢任何帮助或指点!

答案1

首先,我鼓励您查看 Nmap 的 XML 输出(使用标志可用-oX),这是官方支持的机器可读输出格式。 Greppable(-oG.gnmap)输出已弃用,因此不包含 Nmap 新功能(如 traceroute 和 NSE 脚本)的有用信息。

为了直接回答你的问题,

  1. 匹配逗号或空格的问题会导致错误,因为|必须转义交替竖线字符 ( ),而不是逗号。此外,您可能总是想匹配空格字符,但有时只匹配逗号。我会这样做:

    ,\?\s
    

我没有使用分组,因为没有交替(“或”管道)。

  1. sed不会打印您不想要的“线条”,而是打印模式空间。sed 信息页面解释了 sed 的工作原理,是编写 sed 脚本的绝佳参考。您实际上有 2 个空间可供使用,并且当您使用该p命令时,sed 将打印模式空间的所有内容。

作为如何进行此操作的一个例子,下面是我对 sed 脚本的看法,该脚本仅从文件中打印端口信息.gnmap

#!/usr/bin/sed -n 

#First, strip the beginning (Host and Ports labels) off
s/.*Ports: //

#Now match a port entry, consuming the optional comma and whitespace
#The comma and whitespace are replaced with a newline
s_\([0-9]\{1,5\}/[^/]*/[^/]*/[^/]*/[^/]*/[^/]*/[^/]*/\),\?\s_\1\n_

#If we made a successful substitution, jump to :matched, 
t matched
#otherwise skip to the next input line
d

:matched
#Print the pattern space up to the first newline
P
#Then delete up to the first newline and start over with what's left
D

所有这些放在一行中,看起来就像这样:

sed -n -e 's/.*Ports: //;s_\([0-9]\{1,5\}/[^/]*/[^/]*/[^/]*/[^/]*/[^/]*/[^/]*/\),\?\s_\1\n_;t matched;d;:matched;P;D' file.gnmap

还要注意,您不能指望端口规范中的某些字段始终为空。例如,如果对 RPC 服务进行了版本检测,则 SunRPC 信息字段将被填充。

相关内容