Backup users crontab
November 11th, 2006
Typically, when servers are migrated or crash the data and home directories are saved. However, too often
user crontabs are not saved. I implemented a script to backup all user crontabs. You can run this in /etc/cron.daily/
or in a backup script of some kind.
First you must make a secure directory to backup the crontabs:
root@www:/data # mkdir /data/cronjobs/
root@www:/data # chmod 700 cronjobs
The script gets a list of users from /etc/passwd and loops through that list saving the output of crontab -u USERNAME -l to a file called $_USER-cron.jobs:
for _USER in `cat /etc/passwd | awk -F: '{print $1}'`
do
crontab -l -u $_USER 2>/dev/null >/data/cronjobs/$_USER-cron.jobs
done
Or you can run the commands in a list via roots crontab and it will backup itself:
0 * * * * for _USER in `cat /etc/passwd | awk -F: '{print $1}'`; do crontab -l -u $_USER 2>/dev/null >/data/cronjobs/$_USER-cron.jobs; done
Another option is to save in the users home, I chose ~/.cron.jobs.bak. (They of course cannot use that
filename for anything else.):
for _USER in `cat /etc/passwd | awk -F: '{print $1}'`
do
if [ -d /home/$_USER/ ]
then
crontab -l -u $_USER 2>/dev/null >/home/$_USER/.cron.jobs.bak
fi
done
Or if you have a configuration where your home directories are not stored in /home/username:
for USER_HOME in `cat /etc/passwd | awk -F: '{print $1 ":" $6}'`
do
_USER=`echo $USER_HOME | awk -F: '{print $1}'`
_HOME=`echo $USER_HOME | awk -F: '{print $2}'`
if [ -d $_HOME ]
then
crontab -l -u $_USER 2>/dev/null >$_HOME/.cron.jobs.bak
fi
done
In addition, the last is the most portable solution.
Leave a Reply