使用 SED 匹配 gnmap 欄位的模式

使用 SED 匹配 gnmap 欄位的模式

我正在測試使用 Splunk for 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 較新功能(例如追蹤路由和 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 資訊欄位。

相關內容