按服务和ip过滤输出

时间:2018-01-24 22:09:52

标签: bash awk

我正在尝试解析NMAP输出文件以在终端中显示特定字符​​串。

这是我到目前为止所做的:

#!/bin/bash

for y in $(cat out.txt | grep -E 'tcp*open' | awk '{print$2}' | sort | uniq)
do
        echo "$y"
        for z in $(cat out.txt | grep -E "(([0-9]{1,3}\.){3}[0-9]{1,3} | awk '{print$NF}')
              echo "$z"      
        done
done

这有用吗?

2 个答案:

答案 0 :(得分:1)

我不确定它是否必须是bash,所以我做了bash和awk:

Awk: -

awk '/Nmap/{ip = $NF}$2 == "open"{type[$NF][i++] = ip}
     END{for(n in type){print n RT "===============";
           for(i in type[n])print type[n][i];print RT}}' input_file

Bash: -

#!/usr/bin/env bash

declare -A type

#set -xv
while read -ra array
do
    [[ -z "${array[0]}" ]] && continue

    [[ "${array[0]}" == Nmap ]] && ip=${array[-1]}

    [[ "${array[1]}" == open ]] && type[${array[-1]}]+=" $ip"
done<input_file

for t in "${!type[@]}"
do
    echo -e "$t\\n==============="
    for i in ${type[$t]}
    do
        echo "$i"
    done
    echo ""
done

答案 1 :(得分:0)

首先我尝试修改你的代码,但看起来很糟糕。 只是使用bash函数,我会说:

#!/bin/bash

declare -A hash

while read line; do
    if [[ $line =~ ^Nmap\ scan\ report\ for\ ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
        ip=${BASH_REMATCH[1]}
    elif [[ $line =~ ^[0-9]+/(tcp|udp)\ +[^\ ]+\ +([^\ ]+) ]]; then
        proto=${BASH_REMATCH[2]}
        if [ -x ${hash[$proto]} ]; then
            hash[$proto]=$ip
        else
            hash[$proto]="${hash[$proto]},$ip"
        fi
    fi
done < NMAP_all_hosts.txt

for proto in ${!hash[@]}; do
    echo $proto
    echo ============
    IFS=','
    for ip in ${hash[$proto]}; do
        echo $ip
    done
    echo
done