Pinglog

From Omnia
Jump to navigation Jump to search
#!/bin/bash

# pinglog
# purpose: ping target and log up and down change states
# author: Kenneth Burgener <kenneth@oeey.com> March 2011

# INITIALIZE VARIABLES
STATE="DOWN"
TARGET="$1"
SLEEP=1
LOGFILE="$0.log"
DOT=true
LASTUP=`date +%s`

# CHECK COMMAND LINE PARAMETERS
if [ "$1" = "" ] ; then
  echo "Usage: $0 <target> [interval]"
  exit 1
fi
if [ "$2" != "" ] ; then
  SLEEP=$2
fi

# LOG TO FILE AND SCREEN
function log {
  echo $1 >> $LOGFILE
  echo $1
}

# HEADER
log "= PINGING $1 EVERY $SLEEP SECONDS... ="

# INITIAL STATE
ping -c 1 -w 1 $TARGET > /dev/null
if [ $? -eq 0 ] ; then
  log "UP:    `date`"
  STATE="UP"
else
  log "DOWN:  `date`"
  STATE="DOWN"
fi

# MAIN LOOP
while true ; do

  ping -c 1 -w 1 $TARGET > /dev/null
  if [ $? -eq 0 ] ; then
    if [ "$STATE" = "DOWN" ] ; then
      log "UP: `date`"
      STATE="UP"
      log "OUTAGE:  $(( `date +%s` - $LASTUP )) seconds"
    fi
  else
    if [ "$STATE" = "UP" ] ; then
      log "DOWN: `date`"
      STATE="DOWN"
      LASTUP=`date +%s`
    fi
  fi

  if [ $DOT ] ; then
    echo -n "."
  fi

  sleep $SLEEP

done

keywords