Today we will show you how to check the size of a folder with Monit using a shell script and to send alert mail in case of exceeding an allowable certain size limit.
If you didn’t yet install Monit on your server you can check this article:
1./ Create the Check Folder Size Script
– Let’s create the bash script foldersizecheck.sh:
# sudo mkdir -p /root/scripts # sudo vi /root/scripts/foldersizecheck.sh
– Paste the following lines which will check the size of a folder:
#!/bin/bash #capture first passed variable FOLDER_PATH=$1 #capture second passed variable REFERENCE_SIZE=$2 #calculate size of folder SIZE=$(/usr/bin/du -s $FOLDER_PATH | /usr/bin/awk '{print $1}') #convert size to MB MBSIZE=$((SIZE / 1024)) #output size so Monit can capture it echo "$FOLDER_PATH - $MBSIZE MB" #provide status code for alert if [[ $MBSIZE -gt $(( $REFERENCE_SIZE )) ]]; then exit 1 fi
– Make the script executable using the following command:
# sudo chmod +x /root/scripts/foldersizecheck.sh
– Run the script and pass the FOLDER_PATH variable and the REFERENCE_SIZE in megabytes to check if the script working properly:
# sudo bash /root/scripts/foldersizecheck.sh /home/lotfi/ 90
You will see this output with the size of folder, here the output size is 100 MB
/home/lotfi/ - 100 MB
2./ Configure Monit to Check Folder Size
– Create a Monit configuration file under the /etc/monit.d/ directory
# sudo vi /etc/monit/conf.d/foldersize_check check program Home_FileSize with path "/root/scripts/foldersizecheck.sh /home/lotfi/ 90" every 300 cycles if status != 0 then alert
– Monit will check the size of the folder /home/lotfi/ every 300 cycles (the Monit interval defined in the /etc/monit/monitrc). If the size of the folder /home/lotfi is greater than 90 MB Monit will send an email alert.
– Test Monit syntax is valid using the following command:
# sudo monit -t
– Reload Monit if there were no errors using the following command:
# sudo service monit reload
– In the case of of exceeding the allowable size limit you have to get an failed status like in the below picture.
– And Monit automatically will send an email alert.
We hope this tutorial was enough Helpful. If you need more information, or have any questions, just comment below and we will be glad to assist you!
PS. If you like this post please share it with your friends on the social networks using the buttons below.Thanks.