How to Recover Crontab Entries After Accidentally Typing crontab -r

Valic —  February 12, 2013 — Leave a comment

Few days ago I typed crontab -r instead of crontab -e. Well, my crontab was immediately deleted, without any warning. The first thing that I’ve done was to check if there was some backups on the server. As usual, there was no backups on my server.

So..If you accidentally type crontab -r instead of crontab -e , I have the solution for you:

In the system logs /var/logs/ are stored all crontab-calls of your system and you can easily extract them. Depending on your system you need to  cat and grep all crontab lines from the /var/log/syslog* files like this:

cat /var/log/syslog | grep -i "`which cron`" > cron_recovery_file

`which cron` will automatically be replaced by /usr/sbin/cron on Debian.

You need also extract all data from older messages logs stored as .gz archives:

gzip -d /var/log/syslog*.gz -c | grep -i "`which cron`" >> cron_recovery_file

In this moment you have a file called cron_recovery_file  that contains all your crontab-calls.

Your file will look like this now:

Feb 12 19:00:01 debian-tutorials /USR/SBIN/CRON[53198]: (root) CMD (crontab_command > /dev/null 2>&1)
Feb 12 19:00:01 debian-tutorials /USR/SBIN/CRON[53199]: (root) CMD (/scripts/backups > /dev/null 2>&1)
Feb 12 19:00:01 debian-tutorials /USR/SBIN/CRON[53200]: (root) CMD (mysql -u root --password=************ -e "flush query cache"; > /dev/null 2>&1)
Feb 12 19:09:01 debian-tutorials /USR/SBIN/CRON[53277]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -n 200 -r -0 rm)
Feb 12 19:17:01 debian-tutorials /USR/SBIN/CRON[53288]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Feb 12 19:30:01 debian-tutorials /USR/SBIN/CRON[53293]: (root) CMD (another_crontab_command > /dev/null 2>&1)

Now, you need to start with the first line and copy/paste the call ( denotes the stuff in the brackets after ‘CMD’) to a new textfile which will be your new crontab.

To get the time interval for this command you need to use less command to search in your file to find the date/time when this call is repeated. Using less, just type /<command>  this will highlight all occurrences. Once you have extracted this call and recreated it using the appropriate * * * * * <command> syntax  you might delete all its occurrences from cron_recovery_file

cat cron_recovery_file | grep -v "" > cron_recovery_file_new; mv cron_recovery_file_new cron_recovery_file

By repeating these steps,  the file cron_recovery_file  will get smaller and smaller and you will be sure that you have all crontab-calls that were made in the past.


Posts Twitter Facebook

Editor in Chief at Debian-Tutorials, Linux enthusiast.

No Comments

Be the first to start the conversation.

Leave a Reply