A Quick Bash Script for IP Scanner and Port Scanner

This is a very simple, but very useful IP Scanner and Port Scanner. This is not a full blown utility, as you can see there’s only two for loop. It is meant more than anything as a proof of concept, and something you can build your script upon.
IP Scanner:

for host in {1..254}; do
    ping -c1 $network$host &>/dev/null;
    [ $? -eq 0 ] && echo "$network$host is up"

The ip scanner stars with the assignment of a variable containing the network address. Assuming you are scanning a class C network. If not then you would have to modify the script slightly. The rest is the for loop cicling from numbers 1 through 254. In every cycle there is a ping command sending only one packet. The next line check for the exist status of the ping command. If exist status was successful then we can assume the host is up.

Port Scanner:

for port in {1..150}; do 
    (echo > /dev/tcp/$host/$port) &>/dev/null
    [ $? -eq 0 ] && echo "$port open"

There’s a ton of ways that a port scanner can be done in Linux, but for this one we assume no utilities have been installed, and we have to do what we have in a bare bone installation of Linux. The first line assigns the ip address of to host variable. Then the for loop echo into device tcp. If the exist status is successful we got an open port. For this example I just decided to scan from ports 1 through 150.

Detecting Service on The Network
We can expand on the previous command and use it in a more broad situation. For example, if we wanted to find a particular service or server running on the network eg: DNS, SSH, Web, etc.. We could use something like:

for host in {1..254}; do
	ping -c 1 $network$host &> /dev/null 
	[ $? -eq 1 ] && continue 
	(echo > /dev/tcp/$network$host/$port) &>/dev/null
	[ $? -eq 0 ] && [ $port -eq 53 ] && echo "$network$host DNS Server"	

The previous script builds on everything we’ve seen on this tutorial. It loops from ip 1..254 and ping every ip. If it finds a response; then it proceed to test for port 53 (line 6,7). Notice that if the ping command is not successful, the loop continues to the next iteration. In addition, you can add more ports to the script; however, this will decrease scanning time.
Hope you enjoyed the tutorial and be Responsible!

Share This!

One thought on “A Quick Bash Script for IP Scanner and Port Scanner

Leave a Reply

Your email address will not be published.