#!/bin/bash
#
# Sample script for monitoring a httpd server
#
# Heinlein Professional Linux Support GmbH, 8/04
# http://www.heinlein-support.de
#

# Specify file for temporary output
TEMPFILE="/tmp/servercheck.tmp.$$"

# Minimum space for "/" in percent
HDMINFREE="90"

# To-do list
CHECK_WEB=yes
CHECK_ACCOUNTS=yes
CHECK_HDMINFREE=yes
CHECK_LOGINS=yes
CHECK_STATUS=yes

#
# No config changes from this point on.
#

DATUM=`date +'%d %e'`

echo Subject: Server-Status `date +"%b %e"` $HOSTNAME
echo
echo

# Check if web server is running
# Customized for Apache2, use "/etc/init.d/apache"
# and "/usr/sbin/httpd -T" otherwise.
if [ $CHECK_WEB = "yes" ] ; then
if /etc/init.d/apache2 status &> /dev/null && wget --delete-after http://www.domain.local/checkfile.txt &>/dev/null ; then
	# Web server is running! Try reload, perform syntax check before doing so
	if /usr/sbin/httpd2 -t &>/dev/null; then
		/etc/init.d/apache2 reload &>/dev/null && echo "    Web server running and config reload okay."
	else
		echo "### WARNUNG: Reload failed due to CFG error! "
	fi
else
	# Web server not running! Try to launch!
	if /usr/sbin/httpd2 -t &>/dev/null && /etc/init.d/apache2 start &>/dev/null ; then
		echo "### WARNING: Web server was down, restart successful."
	else
		echo "### WARNING: Web server was down, restart FAILED! "
	fi
fi
fi

# Check /etc/passwd for hidden root users
if [ $CHECK_ACCOUNTS = "yes" ] ; then
cat /etc/passwd | grep ":0:" | grep -v ^root: > $TEMPFILE
ACCOUNTS=`cat $TEMPFILE | wc -l`
if [ $ACCOUNTS -ge 1 ] ; then
	echo "### WARNING: Discovered $ACCOUNTS additional accounts with root privileges!"
	cat $TEMPFILE
else
	echo "    No additional root accounts."
fi
fi

# Check for HDMINFREE
if [ $CHECK_HDMINFREE = "yes" ] ; then
KBISFREE=`df | grep /$ | cut -b 52-54`
INODEISFREE=`df -i | grep /$ | cut -b 47-49`
if [ $KBISFREE -ge $HDMINFREE -o $INODEISFREE -ge $HDMINFREE ] ; then
	echo "### WARNING: $KDISFREE% / INODEISFREE% of root partition occupied! "
else
	echo "    Hard disk space for root partition okay."
fi
fi

# Check for failed logins
# Modify grep pattern to reflect your own log format if needed.
if [ $CHECK_LOGINS = "yes" ] ; then
cat /var/log/messages | grep "$DATUM" | grep -i "FAILED " | grep -i "root" | grep -v "tty" |> $TEMPFILE
FAILLOGINCOUNT=`cat $TEMPFILE | wc -l`
if [ $FAILLOGINCOUNT -ge 15 ] ; then
	echo "### WARNING: More than 15 failed root logins! "
elif [ $FAILLOGINCOUNT -ge 1 ] ; then
	echo "    Discovered following failed root logins:"
fi
cat $TEMPFILE
fi

# Generate status:
if [ $CHECK_STATUS = "yes" ] ; then
echo
echo "General server status:"
echo "-----------------------"
echo
echo "Current load in last 15 minutes: `cat /proc/loadavg | sed "s/.* .* \(.*\) .* .*/\1/"`"
echo
echo "Memory usage:"
cat /proc/meminfo | head -n 3
echo
echo "The following users are currently logged on:"
who
fi
echo
echo
#rm $TEMPFILE