Wednesday, December 12, 2012

Port scanning with Bash's TCP socket

Let's say you logged on to a Linux machine and you need to run nmap to find out what ports are open on a specific node, however you do not have sudo access and/or 'nmap' (or nc) is not installed...

Well, here's the solution. Depending on the Bash version that you have, and if it has TCP socket enabled, you can use it's built-in TCP (and UDP) socket to create connections (it's somewhat similar to the client side of 'netcat').

Here's a quick function that can be used for that:

nmap2 () {
[[ $# -ne 1 ]] && echo "Please provide server name" && return 1

for i in {1..9000} ; do
  SERVER="$1"
  PORT=$i
  (echo  > /dev/tcp/$SERVER/$PORT) >& /dev/null &&
   echo "Port $PORT seems to be open"
done
}


And here's an example of running the scan against my gateway:

$ GW=$(route -n | grep '^0.0.0.0' | awk '{print $2}')

$ nmap $GW
The program 'nmap' is currently not installed. You can install it by typing:
sudo apt-get install nmap

$ nmap2 $GW
Port 1720 seems to be open


If you need to increase/decrease the ports that are scanned, simple change the option '{1..9000}' in the script.

No comments: