Check if a remote machine is listening on some specific port, in a *nix system
When working in a distributed environment, I always use to set up some boxes to communicate together using some transport layer (TCP or UDP). So there has been always a need to check whether this or that port is open on some machine, and since ping
command is nothing but an Echo Request on some IP address, I had to look around for a simple but efficient solution and finally crossed one.
Here I share the script that does the checking using the nc
(netcat tool), so you have to make sure it is already installed on your machine.
How To:
Once you are sure to have netcat ready for use, create a bash script with underlines code (either using your favorite text editor or following command line instructions which I will be using right now):
-
Create a bash script with name check_port.sh:
touch check_port.sh
-
Edit the script:
vim check_port.sh
-
Then copy/paste below lines in:
#!/bin/bash # portcheck tool usage() { echo -e "\n USAGE: ./${0##*/} [host|ip] [port] \n" exit } check_port() { local host=${1} local port=${2} if nc -w 5 -z ${host-ip} ${port} 2>/dev/null then echo -e "\a\n => Port ${port} at ${host} is open" else echo -e "\a\n => Port ${port} at ${host} is closed" fi } [[ $# -ne 2 ]] && usage check_port ${1} ${2}
-
Make the script executable:
chmod +x check_port.sh
Usage:
The script is as straightforward as it can be and you can use it by just issuing the script name (in its directory path) followed by an IP address and a Port you want to check, e.g:
cd /path/to/check_port.sh
sh check_port.sh google.com 80
=> Port 80 at google.com.br is open
sh check_port.sh wisebrains.org 8080
=> Port 8080 at wisebrains.org is closed
Note: You can create a link to your script file under your /usr/bin directory so it will be available under your PATH env variable and you are free to use it as a command:
cd /usr/bin
sudo ln -s /path/to/check_port.sh portcheck
Now you can just use the portcheck
command from any path:
portcheck google.com 80
=> Port 80 at google.com.br is open
Written by Marwen Trabelsi
Related protips
3 Responses
I believe the usage function is missing port argument, and should be something like:
echo -e "\n USAGE: ./${0##*/} [host|ip] [port]\n"
Good catch @irakli, I will add the missing argument.
Sort of heavy weaponry: check out nmap.