搜索输出和cat从特定行到特定行并再次搜索

时间:2014-02-06 08:19:41

标签: linux bash sed awk grep

我写了类似的东西:

OUT=$( nmap -p "$port" --script=http-headers.nse "$ip"

例如输出为:

|http-headers: 
|   Server: Apache
|   Vary: Accept-Encoding
|   Content-Type: text/html; charset=utf-8
|   Date: Thu, 06 Feb 2014 07:31:33 GMT
|   Age: 25
|   Connection: close

但我输出的长度是可变的。 所以我希望在输出中的行之间进行搜索(最好使用sedawk)  并检查一个条件。例如,如果从第3行到第8行看到Apache,则回显right

编辑:

我的剧本:

#!/bin/bash

echo "Reading data - headers - both"

if [ $# -ne 3 ]; then
    echo "Usage: ./nmap <port-range> <ip-list> <d || h || b>"
    exit 1
fi

if [ $3 == h ]; then
    while read -r -u3 port; do
    while read -r -u4 ip; do


        echo -n "$ip $port: "
        OUT=$( nmap -p "$port" --script=http-headers.nse "$ip" |
        tail -n 13 | 
        awk -F: '{print $2; exit}')   in other lines
        [[ $OUT == *Apache* ]] && echo right || echo wrong 
    done 4< "$2"
    done 3< "$1"

elif [ $3 == d ]; then
    echo data
elif [ $3 == b ]; then 
    echo both
fi

我想将正确的结果存档...例如:

cat right.txt
ip1  port1
ip2  port2

cat wrong.txt
ip1 port1
ip2 port2

2 个答案:

答案 0 :(得分:1)

你可以使用这个awk:

awk 'NR>=3 && NR<=8 && /Apache/{print "right"}' 

<强>更新

您可以像这样修改代码:

if [ $3 == 'h' ]; then
    while read -r -u3 port; do
      while read -r -u4 ip; do    
         out="$ip $port"
         echo -n "$out: "
         nmap -p "$port" --script=http-headers.nse "$ip" |
         tail -n 13 | grep -q "Apaches" && echo "$out">>right.txt || echo "$out">>wrong.txt
      done 4< "$2"
    done 3< "$1"

elif [ $3 == d ]; then
    echo data
elif [ $3 == b ]; then 
    echo both
fi

答案 1 :(得分:1)

这是修复

#!/bin/bash

echo "Reading data - headers - both"

if [ $# -ne 3 ]; then
    echo "Usage: ./nmap <port-range> <ip-list> <d || h || b>"
    exit 1
fi

headers () {
    join -a1 -a2 -j 2 $2 $1 |while read ip port
     do
        echo -n "$ip $port:"
        OUT=$(nmap -p "$port" --script=http-headers.nse "$ip" | tac | awk -F: 'NR<=13&&/Apache/{print $2; exit}')   
        if [[ "$OUT" == *Apache* ]]; then
            echo $ip $port >> right.txt
        else
            echo $ip $port >> wrong.txt
        fi
     done
} 

case $3 in 
  "h") headers ;;
  "d") echo data;;
  "b") echo both;;
  "*") echo "wrong input"
       exit;;
esac