Friday, June 15, 2012

Restoring a lost crontab

I recently issued a command like this on a production server:

$ crontab -r

I really meant to issue this command instead:

$ crontab -e

(I was trying to add an entry to a very important crontab).

Needless to say, after the command I mistakenly executed, my crontab was gone. 

From crontab's man page:
       -r     The current crontab will be removed.
I went to google to search for some answers and here's what I had to do in order to restore my removed crontab file (I am using CentOS 5):

First, there is directory in /var/spool/cron which holds all crontab files for all users. Mine was gone. So you can't get it from there unless you have a backup (which I didn't). So I couldn't t use it to restore my crontab.

But, there is a log file which turned out to be pretty useful. They are located in /var/logs. The file names are 'cron*'.

So I copied them to a folder to avoid working directly on them:

# cp /var/logs/cron* /home/myuser/cron_restore/
# chown -R myuser:myuser /home/myuser/cron_restore/

Then I extracted all different commands that had been running by crond:

$ cd /home/myuser/cron_restore/
$ cat cron* | grep crond | awk '{ split($0, a, "CMD "); print a[2]; }' | sort | uniq

After running the command, I got a list of all different command run and logged by the cron daemon. Of course, this will only bring you the commands that were still present on the log files. But it happened that I got to recover all I needed. Don't know if it will be the same for someone logging some stuff on a yearly or even monthly basis.

Hope you find this entry useful.

2 comments:

  1. And don't forget to backup all your files in production server! :)

    ReplyDelete
  2. Y sí. Backup tenemos. No sabía nomás que había que hacer backup hasta del `/var/spool/`!!! :-)

    ReplyDelete