#!/bin/bash

# cubiclegraffiti.net 2012-02-09

# This script provides disk utilization for a mountpoint on the target machine. 
# Should work with many flavors of Linux, and possibly UNIX.  (Uses GNU df)

# This script requires: 
# 1) Change NAGCACTIUSER to match the username you use for Nagios/Cacti data collection.
# 2) ssh key set up from the Nagios/Cacti server to the desired user on the remote machine
# 3) 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_disk
#        command_line    $USER1$/check_disk_cacti_nagios.sh $HOSTADDRESS$ $ARG1$ $ARG2$ $ARG3$ nagios
#        }

# In Nagios services.cfg
#define service{
#        use                             service_1_min       
#        host_name                       remotehost1,remotehost2
#        service_description             /var space
#        check_command                   check_disk!/var!80!90
#        max_check_attempts              5
#        contact_groups                  admins
#        }

NAGCACTIUSER="nagios"
        if [[ -z $1 ]]
        then
                echo "Usage:"
                echo "For Cacti: ./check_disk_cacti_nagios.sh <ipaddress> <mount_point>"
                echo "For Nagios: ./check_disk_cacti_nagios.sh <ipaddress> <mount_point> <numeric_warning_threshold> <numeric_critical_threshold> nagios"
                echo "Example: ./check_disk_cacti_nagios.sh 127.0.0.1 <mount_point> 80 90 nagios"
                exit 3
        fi


#DISKDATA=$("ssh -o ConnectTimeout=2 $1 df -k $2" | tail -1)
DISKDATA=$(sudo su - $NAGCACTIUSER -c "ssh -o ConnectTimeout=2 $1 df -k $2" | tail -1)
CAP=$(echo "$DISKDATA" | awk '{print $2}') 
USED_K=$(echo "$DISKDATA" | awk '{print $3}')
USEDPERCENT=$(echo "$DISKDATA" | awk '{print $5}' | cut -d'%' -f 1)
MOUNTED=$(echo "$DISKDATA" | awk '{print $1}')

        if [[ -z $DISKDATA ]]
        then
                echo "No data. Connectivity Problem?"
                exit 3
        fi

	if [[ $5 == "nagios" ]]
	then

		if [[ ${USEDPERCENT} -lt $3 ]]
        	then
                	echo "OK - $USEDPERCENT percent of disk is used. Mounted on $MOUNTED."
                	exit 0
		elif  [[ ${USEDPERCENT} -ge $3 ]]
        	then
          	      if  [[ ${USEDPERCENT} -ge $4 ]]
                        then
                        echo "CRITICAL - Critical threshold is $4 percent disk space used - currently $USEDPERCENT percent used."
                        exit 2
                	else
                        echo "WARNING - Warning threshold is $3 percent disk space used - currently $USEDPERCENT percent used."
                        exit 1
                	fi
        	fi
	else
		echo "USEDK:$USED_K CAP:$CAP"
		exit 3
	fi

exit 3

