#!/bin/bash

# cubiclegraffiti.net 2012-02-06

# This script provides the IDLE CPU of the target machine. 
# Should work with many flavors of Linux and UNIX.

# This script requires: 
# 1) Change NAGCACTIUSER to match the username you use for Nagios/Cacti data collection.
# 2) sar installed on the remote machine (provided by sysstat in some Linux distros)
# 3) ssh key set up from the Nagios/Cacti server to the desired user on the remote machine
# 4) If the user that connects to the remote machine is different from the
# one that Nagios/Cacti run under, then you need something like this in sudoers:
# cacti   ALL=NOPASSWD: /bin/su - <desired_username> *

# In Nagios command.cfg:
# define command{
#        command_name    check_cpu
#        command_line    $USER1$/check_cpu_cacti_nagios.sh $HOSTADDRESS$ $ARG1$ $ARG2$ nagios
#        }

# In Nagios services.cfg
#define service{
#        use                             service_1_min       
#        host_name                       remotehost1,remotehost2
#        service_description             cpu
#        check_command                   check_cpu!30!10
#        max_check_attempts              10
#        contact_groups                  admins
#        }

NAGCACTIUSER="nagios"

	if [[ -z $1 ]]
	then
		echo "Usage:"
		echo "For Cacti: ./check_cpu_cacti_nagios.sh <ipaddress>"
		echo "For Nagios: ./check_cpu_cacti_nagios.sh <ipaddress> <numeric_warning_threshold> <numeric_critical_threshold> nagios"
		echo "Example: ./check_cpu_cacti_nagios.sh 127.0.0.1 20 10 nagios"
		exit 3
	fi

# Select the SAR variable that makes sense for your setup.
#SAR=$("ssh -o ConnectTimeout=2 $1 sar -u 1 1" | sed '1,4d')
SAR=$(sudo su - $NAGCACTIUSER -c "ssh -o ConnectTimeout=2 $1 sar -u 1 1" | sed '1,4d')
COUNT=$(echo "$SAR" | wc -w)

	if [[ $COUNT == 7 ]]
	then
    		CPU=$(echo $SAR | awk '{print $7}' | cut -d . -f 1)
	elif [[ $COUNT == 8 ]]
	then
    		CPU=$(echo $SAR | awk '{print $8}' | cut -d . -f 1)
	else
    		CPU=$(echo $SAR | awk '{print $5}')
	fi

	
	if [[ -z $CPU ]]
	then
		echo "No data. Connectivity Problem?"
		exit 3
	fi
 
	if [[ $4 == "nagios" ]]
	then

		if [[ ${CPU} -ge $2 ]]
        	then
                	echo "CPU OK - $CPU percent idle."
                	exit 0
		elif  [[ ${CPU} -lt $2 ]]
        	then
          	      if  [[ ${CPU} -lt $3 ]]
                        then
                        echo "CRITICAL - CPU less than $3 percent idle - currently $CPU percent idle."
                        exit 2
                	else
                        echo "WARNING - CPU lt $2 idle - $CPU percent idle."
                        exit 1
                	fi
        	fi
	else
		echo "CPU:$CPU"
		exit 0
	fi

exit 3

