linux - 格式化 Masscan 输出

标签 linux bash

Masscan 的 -oG 选项有以下输出:

# Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//

如何使用 awkcutgrepsed 等操作此输出以获得以下格式:

192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443

最佳答案

试试这个:

#!/bin/bash

# define testcontent
content=$(cat << EOT
# Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//
EOT
)

# declare associative array
declare -A dict 

# loop over all ip lines
while read -r ip port; do
   # save ports
   dict[$ip]+="$port "
         # ignore lines start with #, grep ip an port from content 
done < <(sed '/^#/d;s/Host: \([^ ]*\).*Ports: \([0-9]*\).*/\1 \2/' <<< "$content") 

# loop over assocative array
for key in  "${!dict[@]}"; do

   # sort ports in string
   sorted=$(echo "${dict[$key]}" | tr " " "\n" | sort -n | tr "\n" ,)

   # extract leading ,
   ports="${sorted#*,}"

   # print key an ports without tailing ,
   printf "%s %s\n" "$key" "${ports%,*}"
done | sort  

输出

192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443

关于linux - 格式化 Masscan 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56340173/

相关文章:

linux - 有没有办法测量 shell 命令使用了多少内存?

regex - Bash:如何为同一字符串的多个实例 grep 一行?

linux - 正确的系统退出代码

linux - Electron - 如何在 Linux 上创建深层链接

regex - 从字符串中修剪字符串

linux - 如何在 bash 中一次对两行进行排序,使用第二行作为索引?

bash - 使用 heredoc 进行 Shell 扩展

java - 如何在 Ubuntu 上保留两个 Hadoop 版本?

linux - 比较和交换后 CPU 缓存行会刷新吗?

java - 我已经使用 maven 构建了一个 jar 文件,但无法在 linux 中使用 "java"命令执行它