Created
August 15, 2014 08:36
[bash] portscan.sh
This file contains hidden or 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 | |
PROGRAM_NAME=$(basename "$0") | |
VERSION_STR="1.0" | |
help_and_exit() { | |
cat <<EOF | |
Usage: $PROGRAM_NAME [OPTION]... HOST PORT... | |
-t TIMEOUT If TIMEOUT seconds reached, consider the port is closed | |
-h display this help and exit | |
-v output version information and exit | |
EOF | |
exit 0 | |
} | |
version_and_exit() { | |
echo "$PROGRAM_NAME version $VERSION_STR" | |
exit 0 | |
} | |
error() { | |
local retval=$1 | |
shift | |
echo "error: $*" 1>&2 | |
if [ $retval -ne 0 ]; then | |
exit "$retval" | |
fi | |
} | |
timeout_value=1 | |
while getopts "hvt:" opt; do | |
case "$opt" in | |
t) | |
timeout_value=$OPTARG | |
;; | |
h) | |
help_and_exit | |
;; | |
v) | |
version_and_exit | |
;; | |
\?) | |
error 1 "Try '-h' for help" | |
;; | |
esac | |
done | |
if [ "$#" -lt 2 ]; then | |
error 1 "Try '-h' for help" | |
fi | |
shift $(($OPTIND - 1)) | |
host=$1 | |
shift | |
# 1-10 80 81 82 | |
ports="" | |
for arg in "$@"; do | |
if echo "$arg" | grep -- - >&/dev/null; then | |
#range argument | |
IFS="-" read begin end < <(echo "$arg") | |
ports="$ports $(seq $begin $end)" | |
else | |
ports="$ports $arg" | |
fi | |
done | |
for port in $ports; do | |
echo -n "trying $host:$port..." | |
COMMAND="" | |
case "$(uname -s)" in | |
[Ll]inux*) | |
COMMAND=`nc -z -w "$timeout_value" "$host" "$port"` | |
;; | |
[Dd]arwin*) | |
COMMAND=`read -t "$timeout_value" < <(nc -z -w 10 "$host" "$port")` | |
;; | |
esac | |
$COMMAND | |
retval=$? | |
if [ $retval -eq 0 ]; then | |
echo "ok" | |
else | |
echo "fail" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment