Friday, July 29, 2011

Bash Script - Port Scanner

Please be careful! port scanning can be seen as abuse, and get you into trouble (ISP may block your traffic, ect...)

The following bash script works slowly as a port scanner, but may take a long time to scan the 1000 ports that it scanns. It is just a quick example script using 'nc'. The fastest run is with no arguments to scan your localhost. The next fastest would be IP addresses (or domain) in your local network. A slow scan would occur for a non-local IP or domain. or, the slowest scan is a list of hostnames to scan as arguments


Check it out - hope its useful to someone:

#!/bin/bash
#
#       wazopen
#    
#       @copyright - 2011 nairb <code@nairb.us>
#    
#       @license - GNU General Public License V2



findwazopen(){
portscanfile=$(tempfile -p port -s scan.txt)
nc -v -z -w 1 $1 1-1000 >>$portscanfile 2>&1
echo $(cat $portscanfile |grep succeeded|awk '{print $4}')
rm $portscanfile
}

case $(echo ${0##*/} |cut -d '/' -f $(echo ${0##*/} |wc -w)) in
wazopen)
if [ $1 ] ; then
if [ $2 ] ; then
for i in $@ ; do
echo -e "HOST: $i has the following open ports:"
findwazopen $i
done
else
findwazopen $1
fi
else
findwazopen localhost
fi
;;
*)
echo -e "wtf r u trying to do?\n\ncant call this as $0"
;;
esac


although if you have 'nmap' installed, you can do a much easier (and much faster) version like the following 1-liner function to be called on later in the same environment as zopen:

zopen(){ nmap $1 |grep \/ |grep -v nmap |awk '{print $1 " " $3}' ; }

or if you only care about the port numbers:

zopen(){ echo $(nmap $1 |grep \/ |grep -v nmap |awk '{print $1}'|cut -d '/' -f1 ) ; }

another function for a list of hosts:

zopenlist(){ for i in $@ ; do echo -e "$i:\n\t$(echo $(nmap $i |grep \/ |grep -v nmap |awk '{print $1}'|cut -d '/' -f1 ))\n" ;done ; }

or a my favorite, a much better version with better logic and usage of 'awk':

wtfsopen(){ wadopen(){ for i in $@;do echo -e "Host: $i:\nPorts\tServices\n$(nmap $i |awk '/^[0-9].*/ {print $1 " " $3}')";done ; };if [ $(which nmap) ];then if [ $1 ];then wadopen $@;else wadopen localhost;fi;else echo -e "install 'nmap' first";fi; }

and if you find you would like to use any such function often you can just include it in one of your shell's rc instead of making an executable script

1 comment: