#!/usr/bin/perl -w
#
# NMAPPER - nmap wrapper for pentesting V0.2
#
#  - bunker[at]fastwebnet[dot]it
#  - http://rawlab.mindcreations.com
#
use strict;
use Getopt::Std;
use vars qw/ %opt /;

#my $nmap = `which nmap`; chop($nmap);
my $nmap     = "sudo nmap";
my $hostfile = "hosts.txt";
my $ipmatch  = '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}';

print <<BANNER;
 NMAPPER($0): nmap wrapper
 
 - bunker[at]fastwebnet[dot]it
 - http://rawlab.mindcreations.com

 It creates port-related host list from a single target file.
 Useful for host screening during pentest activity.

BANNER

sub usage {
    print <<"USAGE";
    
Syntax: $0 -p port[,port,...] [-I hostfile] [-h] 

Options:
     -h          this help
     -B		 enable banner grabbing (default SYN)
     -p port     port to test [format: 21,22,23,...]
     -I IFILE    hosts file "IFILE" (default "$hostfile") 

USAGE
    exit 0
}

my $opt_string = 'hp:I:B';
getopts($opt_string, \%opt) or &usage;
&usage if $opt{h} or not $opt{p};
$hostfile = $opt{I} if $opt{I};

$|++;

foreach my $port (split /,/,$opt{p}) {
    unless ($port=~/^[0-9]{1,}$/) {
	print STDERR "Error: bad port format ($port)\n";
	exit -1;
    }
    unlink("nmapper-open-$port.txt");
    print " [-] Starting scan for port $port, please wait...\n";
    my @scan;
    if ($opt{B}) {
	@scan = `$nmap -sV -P0 -p $port -iL $hostfile | grep -B 2 open`;
    }
    else {
	@scan = `$nmap -sS -P0 -p $port -iL $hostfile | grep -B 2 open`;
    }
    foreach (@scan) {
	if (/Interesting ports on ($ipmatch):/) {
	    print " [*] Discovered port $port on $1...\n";
	    system("echo \"$1\" >> nmapper-open-$port.txt");
	}
	elsif (/Interesting ports on (.*) \(($ipmatch)\):/) {
	    print " [*] Discovered port $port on $1...\n";
	    system("echo \"$2\" >> nmapper-open-$port.txt");
	}
    }
}

