Bash

用於提取命令輸出的最佳工具

  • December 27, 2021

我想以程式方式處理 nmap 輸出的結果,但無法弄清楚如何獲取輸出並僅提取下面兩個輸出中顯示的協議或埠表的詳細資訊。

我非常有信心我可以使用 awk 來處理表數據 - 但我不能從輸出中提取它……可以使用哪些工具組合來做到這一點?

$ sudo nmap --open -sO 10.100.0.14
Starting Nmap 7.70 ( https://nmap.org ) at 2021-12-27 19:15 AEDT
Warning: 10.100.0.14 giving up on port because retransmission cap hit (10).
Nmap scan report for teichos.mydomain.net (10.100.0.14)
Host is up (0.00030s latency).
Not shown: 250 filtered protocols, 1 closed protocol
PROTOCOL STATE         SERVICE
1        open          icmp
33       open|filtered dccp
80       open|filtered iso-ip
117      open|filtered iatp
136      open|filtered udplite
MAC Address: 6A:3A:ED:33:9E:00 (Unknown)

輸出 2:

$ sudo nmap -sS 10.100.0.14 -p-
Starting Nmap 7.70 ( https://nmap.org ) at 2021-12-27 19:30 AEDT
Nmap scan report for teichos.mydomain.net (10.100.0.14)
Host is up (0.00024s latency).
Not shown: 65533 filtered ports
PORT     STATE SERVICE
22/tcp   open  ssh
9090/tcp open  zeus-admin
MAC Address: 6A:3A:ED:33:9E:00 (Unknown)

我正在尋找的輸出如下(標題不是必需的):

PROTOCOL STATE         SERVICE
1        open          icmp
33       open|filtered dccp
80       open|filtered iso-ip
117      open|filtered iatp
136      open|filtered udplite

PORT     STATE SERVICE
22/tcp   open  ssh
9090/tcp open  zeus-admin

如果給定選項,該nmap實用程序允許輸出易於解析的 XML -oX,這意味著您可以根據需要重新創建表,或從中提取所需的任何資訊。

下面的管道用於xmlstarlet從生成的 XML 文件中提取資訊,並重新創建在普通nmap輸出中找到的表,並插入一個額外的列,其中包含給定“狀態”的“原因”。

的輸出由nmap解析xmlstarlet,它為列分隔符插入#字元(我們不希望成為輸出的一部分的任意字元),並column用於創建最終的對齊表。

sudo nmap -oX - --open -sO localhost |
xmlstarlet sel -t -m /nmaprun/host/ports/port \
   -v @portid -o '#' \
   -v state/@state -o '#' \
   -v state/@reason -o '#' \
   -v service/@name -nl |
column -s '#' -t

範例輸出:

1    open           echo-reply      icmp
4    open|filtered  no-response     ipv4
6    open           proto-response  tcp
17   open           port-unreach    udp
41   open|filtered  no-response     ipv6
50   open|filtered  no-response     esp
51   open|filtered  no-response     ah
97   open|filtered  no-response     etherip
112  open|filtered  no-response     vrrp
137  open|filtered  no-response     mpls-in-ip
240  open|filtered  no-response
255  open|filtered  no-response

同樣,但只提取“過濾”的響應:

sudo nmap -oX - --open -sO localhost |
xmlstarlet sel -t -m '/nmaprun/host/ports/port[contains(state/@state,"filtered")]'  \
   -v @portid -o '#' \
   -v state/@state -o '#' \
   -v state/@reason -o '#' \
   -v service/@name -nl |
column -s '#' -t

範例輸出:

4    open|filtered  no-response  ipv4
41   open|filtered  no-response  ipv6
50   open|filtered  no-response  esp
51   open|filtered  no-response  ah
97   open|filtered  no-response  etherip
112  open|filtered  no-response  vrrp
137  open|filtered  no-response  mpls-in-ip
240  open|filtered  no-response
255  open|filtered  no-response

引用自:https://unix.stackexchange.com/questions/684046