Nov 29, 2007

Checking Disk Space Remotely

Recently I have been looking for ways to monitor disk space of remote servers. We have a Nagios server that has the NRPE plugin. This works fine on Linux, but I recieved an error on FreeBSD. Creating a script to do these checks seemed like it would be quicker than configuring the NRPE plugin to work. Before reinventing the wheel I Googled around and found a very helpful bash script here which can also be found below.
-
#!/bin/bash
ADMIN="me@somewher.com"
ALERT=70
ssh user@ip-address.com df -H > /tmp/df.out
cat /tmp/df.out | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
#echo $output
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge $ALERT ]; then
echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
mail -s "Alert: Almost out of disk space $usep" $ADMIN
fi
done



Although, this does what I am attempting to accomplish, we do not have Bash on our FreeBSD servers. Below you can find my Ksh93 port of the script.

1 #!/usr/local/bin/ksh
2
3 ############################################################################################
4 #
5 # Summary:
6 # This script checks disk usage on remote hosts.
7 # Based on a script by Nixcraft posted on
8 # http://nixcraft.com/shell-scripting/3238-shell-script-check-disk-space-remote-systems.html
9 # which was modified and ported to Ksh by Javier Prats
10 #
11 # Author[s]: Nixcraft, Javier Prats
12 #
13 # Last Modified: 11/28/07
14 #
15 ############################################################################################
16
17 ADMIN="user@emailaddress.com"
18 ALERT=70
19
20 typeset -i usep
21 typeset -A hostnames
22 set -A hostnames hostname1 hostname2 hostname3 hostname4
23
24 for i in ${hostnames[@]}
25 do
26 print "checking $i";
27 ssh user@${i} df -H > ~/df.out
28 cat ~/df.out | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
29
30 do
31 #echo $output
32 usep=`echo $output | awk '{print $1}' | cut -d'%' -f1`
33 partition=`echo $output | awk '{print $2}'`
34 if (($usep >= $ALERT))
35 then echo "Running out of space \"$partition ($usep%)\" on ${i} as on `date +%m/%d/%Y`"|mail -s "Alert: Almost out of disk space $usep" $ADMIN
36 fi
37 done
38 done



A few things will need to be modified. First the "ADMIN" variable on line 17 needs to be a valid email address to recieve alerts on. Second, an array was added to the original script in order to be able to check multiple servers. Change "hostname1", "hostname2", etc on line 22 to valid hostnames you would like to check. Finally, this script uses ssh, so the user on line 27 must be modified to show a real username. On line 18 there is an "ALERT" variable. This sets the threshold for email alerts. By default email alerts are sent when disk usage is above 70%. This value can be changed to whatever is deemed reasonable. Enjoy.