How to check if port 22 is open in Linux

How can I check if TCP port 22 is open in Linux? I need to do some stuff in script and I was wondering if there is easy way to check it.

We can use the following command to check if TCP port 22 is opened or not on your Linux box:

  1. Run the ss command and it will display output if port 22 opened:
    sudo ss -tulpn | grep :22
  2. Another option is to use the netstat:
    sudo netstat -tulpn | grep :22
  3. We can also use the lsof command to see if ssh port 22 status:
    sudo lsof -i:22

Shell script example to check if SSH TCP port 22 opened or not:

sudo lsof -i:22 >/dev/null
if [ $? -eq 0 ]
then
    echo "TCP port 22 opened and sshd is running on Linux"
else
   echo "Sorry: TCP port 22 not found in listing state. Install and enable SSHD service"
fi

See if SSH TCP port 22 opened or not using the ss

Sometimes, the lsof command may not be installed on your distro. In such cases always stick with the ss/netstat as follows:

sudo ss -tulpn | grep -q :22
## sudo netstat -tulpn | grep -q :22 ##
if [ $? -eq 0 ]
then
    echo "TCP port 22 opened and sshd is running/listing on TCP/22 on Linux"
else
   echo "Opps: TCP/22 ssh port not found in listing/open state."
fi

See our guides for more info:


And

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki