#!/bin/bash

# cubiclegraffiti.net 2012-02-06

# This script provides the number of shell users logged into the target machine. 
# Should work with many flavors of Linux and UNIX.

# This script requires: 
# 1) Change the username to match the one 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_users
#        command_line    $USER1$/check_users_cacti_nagios.sh $HOSTADDRESS$ $ARG1$ $ARG2$ nagios
#        }

# In Nagios services.cfg
#define service{
#        use                             service_1_min       
#        host_name                       remotehost1,remotehost2
#        service_description             users
#        check_command                   check_users!40!50
#        max_check_attempts              7
#        contact_groups                  admins
#        }

NAGCACTIUSER="nagios"

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

 # Using | wc -l because many machines I connect to don't have GNU who (-q)

# Select the SAR variable that makes sense for your setup.
#GETCOUNT=$(ssh -o ConnectTimeout=2 $1 who")
GETCOUNT=$(sudo su - $NAGCACTIUSER -c "ssh -o ConnectTimeout=2 $1 who")
COUNT=$(echo "$GETCOUNT" | wc -l)

        if [[ -z $GETCOUNT ]]
        then
		DATACHECK=$(sudo su - $NAGCACTIUSER -c "ssh -o ConnectTimeout=2 $1 uptime")
		if [[ -z $DATACHECK ]]
		then
			echo "No data. Connectivity Problem?"
			exit 3
		else
			COUNT="0"
		fi
	fi

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

		if [[ ${COUNT} -lt $2 ]]
        	then
                	echo "OK - $COUNT users."
                	exit 0
		elif  [[ ${COUNT} -ge $2 ]]
        	then
          	      if  [[ ${COUNT} -ge $3 ]]
                        then
                        echo "CRITICAL - Alert threshold set to $3, currently $COUNT users logged in."
                        exit 2
                	else
                        echo "WARNING - Alert threshold set to $2 users - currently $COUNT users logged in."
                        exit 1
                	fi
        	fi
	else
		echo "users:$COUNT"
		exit 0
	fi

exit 3

