Domanda

I'm trying to make a script that can will run nmap against an ip and tell me if the host is up or not as well as the OS. I want host up and the OS details to be the only things output.

ip=$1
nmap -O $ip |while read -r line; do
if [[ `echo $line|grep "1 host up"`] !=0]
then
    echo "1 Host is up"
else
    echo "No Host"
fi
done

I'm pretty bad at this so any help you can give me will be greatly appreciated :)

EDIT: Sample NMap output as requested

Starting Nmap 5.21 ( http://nmap.org ) at 2013-07-16 13:18 EDT
Nmap scan report for hostname.domain.com (192.168.1.5)
Host is up (0.00028s latency).
Not shown: 997 closed ports
PORT    STATE SERVICE
135/tcp open  msrpc
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address: 78:2B:CB:7E:C7:74 (Unknown)
Device type: general purpose
Running: Microsoft Windows XP
OS details: Microsoft Windows XP SP2 or SP3, or Windows Server 2003
Network Distance: 1 hop

OS detection performed. Please report any incorrect results at http://nmap.org/submit/ 
Nmap done: 1 IP address (1 host up) scanned in 2.44 seconds
È stato utile?

Soluzione 2

You are over-complicating things a bit. Your command could be re-written like this:

if grep "1 host up" <(nmap -O "$i")
then 
    echo "UP"
else 
    echo "DOWN"
fi

Some explanations:

  • We use process substitution (with the <( ) to redirect the output of the command as a parameter to the grep command.
  • The grep command returns zero if it finds a match, and non-zero otherwise. Thus, we can use it directly in the if statement

You can also avoid the if all together like this:

grep "1 host up" <(nmap -O "$i") && echo "UP" || echo "DOWN"

Altri suggerimenti

Here's something you could try:

#! /bin/bash

host=whatever

while read -r line ; do
    if [[ $line =~ ([0-9])+\ hosts?\ up ]] ; then
        host_up="${BASH_REMATCH[1]}"
    elif [[ $line =~ OS\ details:\ (.*) ]] ; then
        host_os="${BASH_REMATCH[1]}"
    fi
done < <(nmap -O $host)

echo "Up: $host_up OS: $host_os"

This uses process substitution to drive the while loop (necessary here - if you do nmap | while, the while ends up in a subshell and can't modify the parent's variables), and a pair of regular expressions to extract the information you need.

Easy to extended later if you need more of the output.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top