MLSC
MLSC

Reputation: 5972

search in output and cat from specific line to specific line and search again

I wrote something like:

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

for example the output is:

|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

but the length of my output is changeable. so I want something to search between lines in my output (better to use sed or awk) and check a condition. for example if it sees Apache from line 3 till line 8 then echo right

Edit:

my script:

#!/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

I want to put my right result in file...for example:

cat right.txt
ip1  port1
ip2  port2

cat wrong.txt
ip1 port1
ip2 port2

Upvotes: 0

Views: 268

Answers (2)

anubhava
anubhava

Reputation: 785721

You can use this awk:

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

UPDATE:

You can modify your code like this:

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

Upvotes: 1

BMW
BMW

Reputation: 45293

Here is the fix

#!/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

Upvotes: 1

Related Questions