colorize(){ GREEN="\033[0;32m" CYAN="\033[0;36m" RED="\033[0;31m" GRAY="\033[0;37m" BLUE="\033[0;34m" YELLOW="\033[0;33m" NORMAL="\033[m" color=\$${1:-NORMAL} # activate color passed as argument echo -ne "`eval echo ${color}`" # read stdin (pipe) and print from it: echo"${*:2}" # Note: if instead of reading from the pipe, you wanted to print # the additional parameters of the function, you could do: # shift; echo $* # back to normal (no color) echo -ne "${NORMAL}" }
success() { colorize GREEN $@ }
failed() { colorize RED $@ }
# check whether port 22 is open type=TCP server=127.0.0.1 port=22 nc -z -w5 $server$port result=$?
# print different colors for different results if [ "$result" != 0 ]; then failed "$type port $server:$port is closed" else success "$type port $server:$port is open" fi
Checking Whether Specific TCP and UDP Ports Are Open
TCP port check
Using telnet
1 2 3 4 5 6 7 8 9 10
~ ❤️ telnet 127.0.0.1 6380 Trying 127.0.0.1... telnet: Unable to connect to remote host: Connection refused ~ ❤️ telnet 127.0.0.1 6379 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. ^] telnet> q Connection closed.
For UDP port detection, I generally only use it as a reference when confirming iptables configuration; this method is not 100% reliable.
Please test carefully and mind the applicable scenarios.
Combining the Two Check Methods
I wrote the two probing methods into one function. If you don’t want to use the failed and success functions above, just replace them with echo.