Skip to content

Instantly share code, notes, and snippets.

@dstd
Created February 11, 2022 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstd/83f039cd842c78088bd35464eb1a52ad to your computer and use it in GitHub Desktop.
Save dstd/83f039cd842c78088bd35464eb1a52ad to your computer and use it in GitHub Desktop.
Utility to monitor host availability changes by ping, with timestamps and durations
#!/bin/bash -l
# Utility to monitor host availability changes by ping, with timestamps and durations
HOST="$1"
ONLINE_INTERVAL=5
OFFLINE_INTERVAL=1
TIMEOUT=500
if [ "x$HOST" == "x" ]; then
echo "usage: $(basename "$0") host"
exit
fi
echo "Monitoring on $HOST. Probe interval: $ONLINE_INTERVAL/$OFFLINE_INTERVAL, Ping timeout: $TIMEOUT"
ping_ex () {
local HOST=$1
local TIMEOUT=$2
local RETRIES=$3
for ((i=0; i < RETRIES; i++)); do
ping -W $TIMEOUT -c1 $HOST > /dev/null 2> /dev/null
if [ $? -eq 0 ]; then
return 0
fi
done
return 1
}
STATE=-1
TIMESTAMP=0
while true
do
NEXT_INTERVAL=0
if [ $STATE -eq 1 ]; then
NEXT_INTERVAL=$ONLINE_INTERVAL
ping_ex "$HOST" "$TIMEOUT" 3
else
NEXT_INTERVAL=$OFFLINE_INTERVAL
ping_ex "$HOST" "$TIMEOUT" 1
fi
RESULT=$(expr "$?" = "0")
if [ $STATE -ne $RESULT ]; then
STATE=$RESULT
if [ $TIMESTAMP -ne 0 ]; then
DT=$(($(date +%s)-TIMESTAMP))
ELAPSED="$(date -ur $DT +%T)";ELAPSED=${ELAPSED#"00:"};
echo " ΔT $ELAPSED"
fi
TIMESTAMP=$(date +%s)
TIME=$(date +"%T")
if [ $STATE -eq 1 ]; then
echo "$TIME – ONLINE"
else
echo "$TIME – OFFLINE"
fi
fi
sleep $NEXT_INTERVAL
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment