Checking uptime on several hosts using bash & ssh


Not a very pretty script, but I guess I should take the time to re-format it, and delegate some of the code to functions. however – it seems to work… It loops forever through some servers calling uptime, and then color-format the output according to $LIMIT, and then sleeping $SLEEP seconds.

update: now using bc, which simplifies thing quite a lot…
update 2: finally made function

#!/bin/bash
#
# Loops forever through servers in $SERVERS
# calls uptime remote using ssh
# color-formats the output according to $LIMIT
# sleeps $SLEEP seconds
#
# © Fredrik Rodland 2009
#
# Feel free to copy or use this script, but don't blame me if
# something goes wrong.
#
# v1.0 made function echo_with_color to reduce duplicate code
# v0.5 using 'bc' instead of bash integer arithmetic
# v0.1 initial version


LIMIT=.50
SERVERS="server1 server2 serverN"
SLEEP=10

NO_COLOUR="\033[0m"; 
RED="\033[1;31m"; 
BLUE="\033[1;34m"; 
GREEN="\033[1;32m"; 

function echo_with_color {
  tmp=`echo "$1 > $LIMIT" |bc`
  if [ $tmp == "1" ]; then
    echo -en "$RED"
  else
    echo -en "$GREEN"
  fi
  echo -ne "$1$NO_COLOUR"
  let "n++"
  if [ $n = "3" ]; then
    n=0
  else
    echo -n ", "
  fi
}

# ugly bugly code
while true; do
  for i in $SERVERS; do
    up=`ssh $i uptime`;
    pre=`echo $up | sed -e "s/\(.*\) \(.*\), \(.*\), \(.*\)/\1/"`
    min_1=`echo $up | sed -e 's/\(.*\) \(.*\), \(.*\), \(.*\)/\2/'`
    min_5=`echo $up | sed -e 's/\(.*\) \(.*\), \(.*\), \(.*\)/\3/'`
    min_15=`echo $up | sed -e 's/\(.*\) \(.*\), \(.*\), \(.*\)/\4/'`

    echo -ne "$BLUE$i$NO_COLOUR: $pre ";
    echo_with_color $min_1
    echo_with_color $min_5
    echo_with_color $min_15
    echo                                                                                                               
  done; 
  sleep $SLEEP; 
done

Leave a Reply

Your email address will not be published.
Required fields are marked:*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>