➜ cat nmap/ports.nmap
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-21 11:30 IST
Warning: 10.10.10.100 giving up on port because retransmission cap hit (10).
Nmap scan report for 10.10.10.100
Host is up (0.26s latency).
Not shown: 65410 closed tcp ports (reset), 111 filtered tcp ports (no-response)
PORT STATE SERVICE
88/tcp open kerberos-sec
135/tcp open msrpc
139/tcp open netbios-ssn
389/tcp open ldap
445/tcp open microsoft-ds
464/tcp open kpasswd5
593/tcp open http-rpc-epmap
636/tcp open ldapssl
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49157/tcp open unknown
49158/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 17.57 seconds
搜索后,我使用这个命令。
cat nmap/ports.nmap | grep 'open' | awk '{ print $1 }' | awk '{print ($0+0)}' | sed -z 's/\n/,/g;s/,$/\n/'
输出:
88,135,139,389,445,464,593,636,49152,49153,49154,49155,49157,49158
有没有比这更简单的命令,任何人都可以帮助我。
答案1
我可能会使用 的 XML 输出nmap
,这使得提取所需信息变得更加容易。
在这里,我使用 获取扫描结果中每个打开端口的端口号xmlstarlet
,然后使用paste
逗号分隔字段将端口号行格式化为单行:
$ nmap -oX - localhost | xmlstarlet sel -t -v '//port[state/@state="open"]/@portid' -nl | paste -s -d, -
22,25,111,2049,7000,7001
如果您想先保存结果,可以分两步进行:
$ nmap -oX nmap.xml localhost
Starting Nmap 7.93 ( https://nmap.org ) at 2022-10-21 08:53 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000057s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 994 closed tcp ports (conn-refused)
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
111/tcp open rpcbind
2049/tcp open nfs
7000/tcp open afs3-fileserver
7001/tcp open afs3-callback
Nmap done: 1 IP address (1 host up) scanned in 6.13 seconds
$ xmlstarlet sel -t -v '//port[state/@state="open"]/@portid' -nl nmap.xml | paste -s -d, -
22,25,111,2049,7000,7001
XPath 查询定位XML 文档中具有子节点且属性值为 value 的//port[state/@state="open"]/@portid
任何节点。对于每个这样的节点,都会提取属性。port
state
state
open
port
portid
如果您只想对已有的内容进行变体,则可以将大部分解析合并到一个awk
调用中:
awk '$2 == "open" { sub("/.*","",$1); print $1 }' nmap.out | paste -s -d, -
open
这会检测第二个字段中的单词,并提取并打印/
第一个字段中 之前的所有内容。与paste
以前一样创建逗号分隔列表。
答案2
cat nmap/ports.nmap | awk -F/ '/open/ {b=b","$1} END {print substr(b,2)}'
就用awk吗?
88,135,139,389,445,464,593,636,49152,49153,49154,49155,49157,49158
答案3
原始命令:
cat nmap/ports.nmap | grep 'open' | awk '{ print $1 }' | awk '{print ($0+0)}' | sed -z 's/\n/,/g;s/,$/\n/'
排序并删除重复端口命令:
cat nmap/ports.nmap | grep 'open' | awk '{ print $1 }' | awk '{print ($0+0)}' | sort | uniq | sed -z 's/\n/,/g;s/,$/\n/'