deleted cron tab file and need to recover it

I ran crontab -r instead of crontab -e and deleted my crontab file. I didn't have a backup and new to recover the deleted file.

Is this possible?

Thanks,

Peter


Solution 1:

Try looking at /var/log/cron to see what has been running and then try to recreate the crontab from that. Its messy but you should be able to restore everything that had previously run. Not so much luck for newer items though. Good luck!

Solution 2:

First of all: Always make backups!

But, it is so easy to mix up crontab -r and crontab -e. I just did this myself.

That's what I did:

You can try to have a look at /var/log/cron and build your crontab again.

  1. Have a look at the logfile
  2. Take the first command and do grep commandname1 /var/log/cron
  3. Figure out the systematic behind the times the command was run
  4. Put that entry to your new crontab
  5. execute cat /var/log/cron | grep -v commandname1. This will exclude the command1 that you already covered.
  6. Take the next command and grep for it
  7. Figure out the systematic behind the times the second command was run
  8. put that entry to your new crontab
  9. execute cat /var/log/cron | grep -v commandname1 | grep -v commandname2
  10. Repeat until you covered all commands

Now you should also execute the grep on older cronlogs to find out jobs that might be run only once in a month.

Solution 3:

Script for full crontab recovery

I made a PHP script that does a full recovery of your crontab, based on the log.

It outputs a single instance of every cron command run by the user for the last week.

I put it here

https://github.com/dangreenisrael/recover_crontab

Here is a sample output:

perl ~/sorttv/sorttv.pl

/usr/local/bin/flexget

bash ~/scripts/sort_sports.sh

~/scripts/play_recently_added.sh

Solution 4:

Ugh can't post a comment on the original question, but a co-worker just showed me a great tool: make an alias in whatever .profile you use for crontab to be crontab -i. The -i flag asks for confirmation before deleting.

So, if you do crontab -e it will proceed to edit as usual, but if you accidentally do crontab -r you are greeted with a confirmation prompt.

Solution 5:

You've got options, but none are particularly pretty. In case you haven't thought of it, if you've got a recent version on a development machine, you can copy it from there ... I only say that because I often forget about copies that may be on other machines, so I assume that you've already tried that.

If your file is too heavily customized to make simply rebuilding it practical, you can always try some low-level forensics. Try googling for tutorials based around sleuthkit and UFS Explorer. People using these tools find widely varying degrees in terms of ease of use and success rates, so as usual, YMMV.