我有这样的网络日志文件:
Nmap scan report for 192.168.1.51
Host is up.
PORT STATE SERVICE
80/tcp open http
443/tcp open https
8080/tcp open http-proxy
443/tcp open https
8080/tcp open http-proxy
8082/tcp filtered redcap
8083/tcp filtered https-alt
Nmap scan report for 192.168.1.201
Host is up.
PORT STATE SERVICE
80/tcp open http
443/tcp filtered https
8281/tcp filtered http-proxy
8080/tcp open sedan
8801/tcp filtered https-alt
Nmap scan report for 192.168.1.17
Host is up.
PORT STATE SERVICE
80/tcp closed http
443/tcp closed https
9081/tcp open ecan
Nmap scan report for 192.168.1.10
Host is up.
PORT STATE SERVICE
80/tcp closed ftp
443/tcp open https
9081/tcp open standard
我想提取 IP 地址以及每个 IP 地址的开放端口计数,因此结果:
192.168.1.10 - 2
192.168.1.201 - 2
192.168.1.51 - 5
192.168.1.17 - 1
答案1
awk
解决方案:
awk 'BEGIN{RS=""; FS="\n"}
{split($1,a," "); host[a[5]] = 0; for (i=1; i<=NF; i++) if (match($i,"open") != 0)
host[a[5]]++} END{for (each in host) print each " - " host[each]}' file
192.168.1.10 - 2
192.168.1.201 - 2
192.168.1.51 - 5
192.168.1.17 - 1
在此命令中,记录分隔符RS
设置为空行“”
,字段分隔符设置为换行符\n
。接下来,awk
分割每条记录的第一行,并捕获分割数组中与 IP 地址相关的第五项。然后,Awk
迭代其余字段,NF
在每个字段中查找字符串“open”。当open
存在时,它将计入主机阵列中的相关 IP 地址。最后,awk
打印结果。
答案2
由于您似乎有一个 nmap 日志文件,因此如果您可以控制 nmap 的调用,请考虑使用(已弃用的)-oG
选项来创建 grepable 输出。例如:
$ nmap -oG /tmp/output.txt localhost
$ awk '/^Host: / && /Ports: / { num=gsub("/open/", ""); print $2, "-", num }' < /tmp/output.txt
127.0.0.1 - 6
这使用 awk 解析 nmap 的 grepable 输出; awk 脚本查找还包含字符串“Ports:”的“Host:”行;然后它计算“/open/”字符串的数量并报告每个主机的数量。
答案3
我将改用下面的awk
方法:
awk 'function output() { print ip, count; count=0 }
/Nmap/ && count { output() }
/Nmap/ { ip=$NF }
/open/ { count++ }
END{ output() }' infile