In this process, we will use a small script that will monitor the available filesystem’s disk space periodically using cron, and if it exceeds a certain percentage threshold the script will send out a mail with a warning message.
To Start With: What Do You Need?
To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges and a console-based text editor of your choice. You should have read the Scheduling tasks with cron process to have a basic understanding of the principles behind the cron system.
The Process
- To begin this process, log in as root and create the following file that will contain our monitoring script:
vi /etc/cron.daily/monitor_disk_space.sh
- Now, put in the following content:
#!/bin/bash
EMAIL="root@localhost"
THRESHOLD=70
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $6 }'
| while read output;
do
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge $THRESHOLD ]; then
(echo "Subject: Alert: Free space low on `hostname -s`, $usep % used
on $partition"; echo)|
sendmail -t $EMAIL
fi
done - Now, save the file and make it executable:
chmod +x /etc/cron.daily/monitor_disk_space.sh
How it works…
We made this script executable and put it in the /etc/cron.daily directory, which is all we need to do to run this script automatically every day via the crond service.
This simple script showed us how easy it is to build monitoring scripts, and this can be a real alternative to installing and configuring big monitoring suites such as Nagios. You can use the shown script as a starting point to expand on, adding further resources that are important to monitor, such as CPU load, available RAM, and so on.
We used a script that executes the Linux command df, which is a tool to report file system disk space usage. From this command’s output, the script then parsed the USE% column (with the Unix tools awk and cut), which gives us the total disk percentage used. This number will then be compared to a threshold the user can set by editing the script and changing the environment variable, THRESHOLD. If the extracted percentage number is higher than our threshold, there will be an email sent to the email address defined with the environment variable, EMAIL (change appropriately if needed).