Saturday, October 6, 2012

Bash Socket Programming : Scan ports using Bash shell's /dev/tcp


In bash shell, a network socket can be opened to pass data through it.
A tcp socket as well as a udp socket can be opened using either of the following

  • /dev/tcp/host/port - The host should be a valid hostname or Internet address, and port should be an integer number or service name. bash attempts to open a TCP connection to the corresponding socket.
  • /dev/udp/host/port - The host shall be a valid hostname or Internet address, and port shall be an integer port number or service name. bash attempts to open a UDP connection to the corresponding socket.

Let us see how to use it for port scanning. Say for example, if we need to find if port 80 is open or closed for google.com, run the following command

$ echo >/dev/tcp/google.com/80 && echo "port 80 is open" || echo "port 80 is closed"

In case if the port is open, the output is received quickly. However, if the port is closed, it takes a long time to get an output.
So we can use the "timeout" utility to  exit the command in case the response is not received within specified time limit.

$ timeout 1 bash -c "echo >/dev/tcp/$host/$port" && echo "port $port is open" || echo "port $port is closed"

  •  bash -c : If the -c option is present,  then  commands  are  read from the string. 

To scan a range of ports, say for example port 1 to 100, do the following

for port in {1..100}
do
    timeout 1 bash -c "echo >/dev/tcp/google.com/$port" && echo "port $port is open" || echo "port $port is closed"
done

No comments:

Post a Comment