Skip to content

Instantly share code, notes, and snippets.

@asuna
Last active January 30, 2024 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asuna/6eadd5de0ea6720d3cff58183554c345 to your computer and use it in GitHub Desktop.
Save asuna/6eadd5de0ea6720d3cff58183554c345 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Check_port <address> <port>
check_port() {
if [ "$(which nc)" != "" ]; then
tool=nc
elif [ "$(which curl)" != "" ]; then
tool=curl
elif [ "$(which telnet)" != "" ]; then
tool=telnet
elif [ -e /dev/tcp ]; then
if [ "$(which gtimeout)" != "" ]; then
tool=gtimeout
elif [ "$(which timeout)" != "" ]; then
tool=timeout
else
tool=devtcp
fi
fi
echo "Using $tool to test access to $1:$2"
case $tool in
nc) nc -v -G 5 -z -w2 $1 $2 ;;
curl) curl --connect-timeout 10 http://$1:$2 ;;
telnet) telnet $1 $2 ;;
gtimeout) gtimeout 1 bash -c "</dev/tcp/${1}/${2} && echo Port is open || echo Port is closed" || echo Connection timeout ;;
timeout) timeout 1 bash -c "</dev/tcp/${1}/${2} && echo Port is open || echo Port is closed" || echo Connection timeout ;;
devtcp) </dev/tcp/${1}/${2} && echo Port is open || echo Port is closed ;;
*) echo "no tools available to test $1 port $2";;
esac
}
export check_port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment