Check if remote host/port is open - Can't use GNU Netcat nor NMap - RHEL 7

Solution 1:

Bash allows you to connect to TCP and/or UDP ports by redirecting to special files:

/dev/tcp/host/port If host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open the corresponding TCP socket.

/dev/udp/host/port If host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open the corresponding UDP socket.

A failure to open or create a file causes the redirection to fail.

So to test if you can connect to port 80 on www.example.com the following should work:

echo -n > /dev/tcp/www.example.com/80

If the port is blocked you either get a "connection refused" message or a timeout.

Solution 2:

Though Ncat does not yet support -z, you can get the same behavior with shell redirection:

$ ncat google.com 80 </dev/null >/dev/null && echo "yes"
yes
$ ncat google.com 81 </dev/null >/dev/null && echo "yes"
Ncat: Connection timed out.
$ ncat scanme.nmap.org 1234 </dev/null >/dev/null && echo "yes"
Ncat: Connection refused.

The connect timeout can be adjusted with the -w option.

EDIT: Ncat 7.25BETA2 introduced the -z option which works as it does with GNU netcat, but only on single ports. If you need to scan port ranges, you should be using Nmap.


Solution 3:

Neither netcat, telnet nor nmap are needed. Bash is simpler, portable and more efficient.

Open check

(>/dev/tcp/example.com/80) &>/dev/null && echo "Open" 

Open/Closed Check

(>/dev/tcp/example.com/80) &>/dev/null && echo "Open" || echo "Closed"

Port Range Check

for i in $(seq 80 88); do (>/dev/tcp/example.com/80/$i) &>/dev/null && echo $i Open|| echo $i Closed; done

Tags:

Netcat

Nmap

Rhel7