|
#!/bin/bash
##---------------------------------------------------------------------------##
#
# Script: ishostavail
# Author: Brian <genius@groupbcl.ca> :)
# Date: August 2001
#
# usage: ishostavail [-v] [-t] host [port]
#
# ishostavail is used to determine quickly if a given host is online by
# attempting to open a socket to it (using TCL). If the open is
# successful, the script assumes the host was reachable and returns 0,
# else it returns 1.
#
# By default the script attempts to open port 80 (http) on the assumption
# you're trying to determine if a WWW host is available. You can over-
# the default port by specifying its name or number after the host.
#
# The -v switch enables verbose mode; otherwise this script produces
# no output.
#
# The -t (test) switch causes 0 to be returned on POSIX ECONNREFUSED,
# on the assumption you are testing to see if the host even exists,
# regardless of whether or not you can connect to a specified port.
#
##---------------------------------------------------------------------------##
# BUUS: This script is part of Brian's Useful Utilities Set
VERBOSE=false
TEST=false
PORT="http"
##---------------------------------------------------------------------------##
# ErrorMsg - prints $1 on stderr; exits if $2 is "exit"
##---------------------------------------------------------------------------##
function ErrorMsg {
echo "$1" >&2
[ "$2" = "exit" ] && exit 1
}
##---------------------------------------------------------------------------##
# M A I N P R O C E S S I N G
##---------------------------------------------------------------------------##
[ -z "$1" ] && ErrorMsg "usage: ishostavail [-v] [-t] host [port]" exit
#--- Check the command line ---
for PARM in $*
do
case $PARM in
-t) TEST=true;;
-v) VERBOSE=true;;
*)
if [ -z "$HOST" ]
then HOST=$PARM
else PORT=$PARM
fi
;;
esac
done
#----- If the host contains a ":", assume the user meant host:port -----
COLON_POS=$(expr index "$HOST" ":")
if [ $COLON_POS -gt 0 ]
then
PORT=$(expr substr "$HOST" $((COLON_POS + 1)) 99)
HOST=$(expr substr "$HOST" 1 $((COLON_POS - 1)) )
fi
#----- Try to contact the host -----
$VERBOSE && echo -n "ishostavail $HOST/$PORT: "
echo '
set Host [lindex $argv 1]
set Port [lindex $argv 2]
set Test [lindex $argv 3]
set Verbose [lindex $argv 4]
set ExitCode 0
if {[catch {set SOCKET [socket "$Host" "$Port"]} SockErr]} {
if {[string range $errorCode 0 3] == "NONE" } { set ExitCode 1 }
if {[string range $errorCode 0 16] == "POSIX ENETUNREACH" } { set ExitCode 1 }
if {[string range $errorCode 0 17] == "POSIX EHOSTUNREACH" } { set ExitCode 1 }
if {[string range $errorCode 0 17] == "POSIX ECONNREFUSED" } {
if {$Test == "false"} { set ExitCode 1 }
}
if {$Verbose == "true"} {puts -nonewline stdout "$errorCode "}
}
exit $ExitCode
' | /usr/bin/tclsh - $HOST $PORT $TEST $VERBOSE
RC=$?
$VERBOSE && echo -n "(RC $RC) "
#----- Set the return code and exit -----
X="OK"; [ $RC != 0 ] && X="FAIL"
$VERBOSE && echo $X
exit $RC
# vim: tabstop=4
|