#!/bin/bash
#
CMD=$(basename $0)
CMDVER="1.0"
CMDSTR="$CMD v$CMDVER (2018/07)"

usage()
{
	echo "
$CMDSTR - performs knock on remote server ports (using nmap)

usage: $CMD [options] remotehost port(s)

options:
 -t|--timeout N		set timeout to N, in seconds (now: $timeout)
" >&2
	exit 127
}

# (MAIN)

ports=
remote=
timeout=201

while [ $# != 0 ]
do
  case $1 in
    -t|--timeout)
    	shift
	[ $# = 0 ] && {
		echo -e "\n  error: --timeout needs a numeric argument\n" >&2
		usage
	}
	timeout=$1
	;;
     -*)	usage ;;
     [0-9]*)	ports="$ports $1" ;;
     *)
     	[ "X$remote" != "X" ] && usage
	remote=$1
	;;
  esac
  shift
done

[ $# != 0 ] && usage
[ "X$remote" = "X" ] && usage
[ "X$ports" = "X" ] && usage

for port in $ports
do
	echo -n "  knocking $remote on port $port ... "
	nmap -Pn --host_timeout ${timeout}s --max-retries 0 -p $port $remote >/dev/null || exit $?
	echo "ok"
done

exit 0
