Home > Enterprise >  How to check if a connection can be made to a port in bash
How to check if a connection can be made to a port in bash

Time:09-27

I would like to check if I can connect to a port or not from within a bash script

Based on the answer to a similar question I tried running

nc -zvw10 <host> <port>

and check if the status code is 0/1

but many times it returns "Connection refused" and exits the script (there doesnt seem to be a return code)

I only want to exit the script if it returns a 0, which means a connection is made.

CodePudding user response:

You can redirect the output and error stream to /dev/null using nc -zvw10 <host> <port> &>/dev/null

CodePudding user response:

Use boolean operators:

#!/bin/bash
nc -zvw10 $1 $2 && exit 1 || echo "continue."
echo "It continues."

And on a closed port, it stops:

bash bar.sh localhost 2048
nc: connect to localhost port 2048 (tcp) failed: Connection refused
continue.
It continues.

So on open port:

bash bar.sh localhost 2049
Connection to localhost 2049 port [tcp/nfs] succeeded!
  • Related