Cron jobs
First a script to get the information that I need from the server. We can use the “df” command which will show information about the file system. This along with some parsing commands will give us the results that we need. The script goes something like this:
#!/bin/bash
date >> driveSpace.log
fspace=`df -h | grep sda | awk ‘{ print $5 }’`
echo “There is “$fspace” disk space left.” >> ~/driveSpace.log
This little script creates a log file in my home directory (called driveSpace.log) which will get a “date” stamp and a single line telling me how much disk space is left on the drive. I saved this as diskSpace.sh and also left it located in my home directory. Next we will need to setup the cron command that will allow this script to run once a day to check the disk space. In order to run the cron process as a non-root user you will need to have your account listed in the /etc/cron.allow file. Now I’m working on an Ubuntu server and by default there is no cron.allow file you need to create it. If you don’t the cron job will never execute. My test user is called Jake so I will add him to the cron.allow file. Use the sudo command to create the necessary file:
sudo echo Jake >> /etc/cron.allow
This will create the file and also put Jake in the file so that he now has rights to run his own cron jobs. Next we can go ahead an create a crontab file for Jake. Enter the following:
crontab -e
This will create a new crontab file (if one doesn’t exist already) and then bring you into that crontab file for the user. You’ll see on the top commented out the syntax that we need to use in order to create cron jobs. For our script we are going to use the following syntax:
01 04 * * * /home/Jake/diskSpace.sh
This syntax says that I want to run this script at 4:01AM every day of the week and output to the logfile specified in the script. This way I can monitor the log file to check how full my system disk is. You can get more fancy with a script like this as well making checks to see if the disk is at a certain threashold, or to email you when it breaks a certain threashold. This is just a basic example of how powerful scripting can be along side creating tasks to automate the process.