Last active
May 9, 2018 19:21
-
-
Save yesmar/4c0c20812604b66414de616887dddf28 to your computer and use it in GitHub Desktop.
TCP port scanner in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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
This prints
N
in about a second:This still returns almost immediately and prints
Y
: