Skip to content

Instantly share code, notes, and snippets.

@yesmar
Last active May 9, 2018 19:21
Show Gist options
  • Save yesmar/4c0c20812604b66414de616887dddf28 to your computer and use it in GitHub Desktop.
Save yesmar/4c0c20812604b66414de616887dddf28 to your computer and use it in GitHub Desktop.
TCP port scanner in Bash
#!/bin/bash
# strobe.bash
# Bash TCP/IP port scanner.
# http://www.catonmat.net/blog/tcp-port-scanner-in-bash/
# alarm() by Coder.C, scan() by Peteris Krumins, wrapped by Yesmar.
# Usage: strobe.bash <target> <protocol> <low[-high][,...]>
# You can specify 80 or 22,80 or 22,80,90-100,10000-25000,43001
# It's best to do this: strobe.bash localhost tcp 22,80,443 2>&1 | grep open
# This script requires the presence of /dev/tcp.
script=$(basename "$0")
function usage() {
echo "Usage: $script <target> <proto> <low[-high][,...]>"
}
function alarm() {
timeout=$1; shift;
bash -c "$@" &
pid=$!
{
sleep "$timeout"
kill $pid 2> /dev/null
} &
wait $pid 2> /dev/null
return $?
}
scan() {
if [[ -z $1 || -z $2 || -z $3 ]]; then
usage
return
fi
local host=$1
local proto=$2
local ports=()
case $3 in
*,*) IFS=, read -ra ports <<< "$3" ;;
*-*) IFS=- read -r start end <<< "$3"
for ((port=start; port <= end; port++)); do ports+=($port); done ;;
*) ports+=($3) ;;
esac
for port in "${ports[@]}"; do
alarm 1 "echo >/dev/$proto/$host/$port &&
echo \"port $port/$proto is open\"" ||
echo "port $port/$proto is closed"
done
}
if [ $# -lt 2 ]; then
usage
exit 1
else
scan "$@"
exit 0
fi
@yesmar
Copy link
Author

yesmar commented Feb 4, 2017

This prints N in about a second:

alarm 1 "echo >/dev/tcp/google.com/230" && echo "Y" || echo "N"

This still returns almost immediately and prints Y:

alarm 60 "echo >/dev/tcp/google.com/80" && echo "Y" || echo "N"

@yesmar
Copy link
Author

yesmar commented May 9, 2018

This script has been useful in scanning minicomputers with flaky TCP/IP stacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment