36 lines
1.3 KiB
Bash
36 lines
1.3 KiB
Bash
## Stop installing tools just to check if a port is open. Bash has it built in.
|
|
|
|
# Source: https://www.reddit.com/r/bash/comments/1rcgyb7/stop_installing_tools_just_to_check_if_a_port_is/
|
|
|
|
# Instead of:
|
|
telnet host 443
|
|
# or
|
|
nmap host -p 443
|
|
# Just use:
|
|
echo > /dev/tcp/host/443 && echo "open" || echo "closed"
|
|
|
|
# No tools required. No sudo. No package manager. Works on any machine with bash.
|
|
|
|
# /dev/tcp is a bash built-in pseudo-device. Bash handles the TCP connection itself — the kernel never sees a file open on /dev/tcp.
|
|
|
|
# Real world examples:
|
|
|
|
# Check if SSH is up
|
|
echo > /dev/tcp/192.168.1.100/22 && echo "SSH up" || echo "SSH down"
|
|
|
|
# Check if your web server is listening
|
|
echo > /dev/tcp/localhost/80 && echo "nginx up" || echo "nginx down"
|
|
|
|
# Check SSL port before running a cert check
|
|
echo > /dev/tcp/example.com/443 && echo "open" || echo "closed"
|
|
|
|
# Loop until a service comes up (great for scripts)
|
|
until echo > /dev/tcp/localhost/5432; do
|
|
echo "waiting for postgres..."
|
|
sleep 2
|
|
done
|
|
|
|
# That last one is the killer use case — waiting for a service to become available in a deploy script without installing netcat or curl or anything else.
|
|
# One caveat: this is bash-specific. Won't work in sh, zsh, or fish. If portability matters, use nc -z host port instead.
|
|
# Works on Linux and macOS.
|