Find open ports on the Linux server using a script

Find open ports on the Linux server using a script

Create a .sh file with below script and set execute permission for the scrip file.

#vi portscan.sh


#!/bin/bash
#The port numbers

  • PORT1=21 #ftp
  • PORT2=22 #ssh
  • PORT3=25 #smtp
  • PORT4=53 #dns
  • PORT5=80 #http
  • PORT6=110 #POP3
  • PORT7=143 #IMAP
  • PORT8=443 #https
  • PORT9=1433 #MSSQL
  • PORT10=3306 #MYSQL
  • PORT11=3389 #Microsoft-RDP
  • PORT12=5432 #PostgreSQL

read -p “Enter the Server IP/HOSTNAME : ” HOSTNAME #Enter the Host Name to check the Open Ports
echo “”
echo “Checking open/closed ports on the host $HOSTNAME”, Please wait….
echo “”
if ping -c2 $HOSTNAME |grep -i “time=”
then
echo $HOSTNAME is up
else
echo “$HOSTNAME is down or unable to ping”
fi
echo “”
echo “Checking the port status of $HOSTNAME”, Please wait….
echo “”
if nmap -p$PORT1 $HOSTNAME | grep -q open
then
echo $PORT1 is open
else
echo $PORT1 is down
fi
if nmap -p$PORT2 $HOSTNAME | grep -q open
then
echo $PORT2 is open
else
echo $PORT2 is down
fi
if nmap -p$PORT3 $HOSTNAME | grep -q open
then
echo $PORT3 is open
else

echo $PORT3 is down
fi
if nmap -p$PORT4 $HOSTNAME | grep -q open
then
echo $PORT4 is open
else
echo $PORT4 is down
fi
if nmap -p$PORT5 $HOSTNAME | grep -q open
then
echo $PORT5 is open
else
echo $PORT5 is down
fi
if nmap -p$PORT6 $HOSTNAME | grep -q open
then
echo $PORT6 is open
else
echo $PORT6 is down
fi
if nmap -p$PORT7 $HOSTNAME | grep -q open
then
echo $PORT7 is open
else
echo $PORT7 is down
fi
if nmap -p$PORT8 $HOSTNAME | grep -q open
then
echo $PORT8 is open
else
echo $PORT8 is down
fi
if nmap -p$PORT9 $HOSTNAME | grep -q open
then
echo $PORT9 is open
else
echo $PORT9 is down
fi
if nmap -p$PORT10 $HOSTNAME | grep -q open
then
echo $PORT10 is open
else
echo $PORT10 is down
fi
if nmap -p$PORT11 $HOSTNAME | grep -q open
then
echo $PORT11 is open
else
echo $PORT11 is down
fi

if nmap -p$PORT12 $HOSTNAME | grep -q open
then
echo $PORT12 is open
else
echo $PORT12 is down
fi


# chmod +x portscan.sh

# sh portscan.sh

Enter the Server IP/HOSTNAME : localhost (any server name or ip address)

(You will see the output as below)


Checking open/closed ports on the host localhost, Please wait….

64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.037 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.039 ms
localhost is up

Checking the port status of localhost, Please wait….

  • 21 is down
  • 22 is open
  • 25 is open
  • 53 is down
  • 80 is down
  • 110 is down
  • 143 is down
  • 443 is down
  • 1433 is down
  • 3306 is down
  • 3389 is down

Hope this helped in finding the open ports on Linux using a script.

Here is a related post you may be interested in: How to Fix – When Xenserver Host Stuck in Maintenance Mode

To get more updates you can follow us on Facebook, Twitter, LinkedIn

Subscribe to get free blog content to your Inbox
Loading

Written by actsupp-r0cks