13

I was trying to edit crontab in the terminal, and I accidentally typed crontab -r instead of crontab -e. Who would figure such dangerous command would sit right next to the letter to edit the crontab? Moreover, I am still trying to figure out how does crontab -r not ask you for confirmation?

Regardless of my lack of credibility as to how this is possible, my question is: am I able to recover the lost crontab?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

3 Answers3

8

You can find your cron jobs from the log if once it has executed before. Check /var/log/cron.

You do not have any recovery option other than third party recovery tools.

  • Any hints on how I can check I am not missing something? What if there was some weekly, or monthly task? Would I have to go line by line until the beginning of last month to find out if I have some less common cronjob running? – Miguel Mesquita Alfaiate Dec 01 '17 at 09:53
  • I think you have to go line by line for last one month. Sorry – Muhammed Sherief Dec 01 '17 at 11:29
  • No need for "line by line". Use grep with either -o or piped into sed/awk/cut/etc to extract just the command, and then piped into sort -u. – phemmer Dec 01 '17 at 13:31
  • 3
    You'll still need to go line-by-line to work out the schedules if they aren't simply daily or weekly. Something like awk '$5 ~ "^CROND" && $6 == "(username)" { print }' /var/log/cron | sort -t ' ' -k 8 will show the entries for username sorted by command, which should make it easier to see the intervals between them so you can recreate their schedules. – James Sneeringer Dec 01 '17 at 14:28
  • @JamesSneeringer that is definitely witchcraft! thumbs up for that! – Miguel Mesquita Alfaiate Dec 01 '17 at 15:42
  • @BlunT - Thanks! I can't edit my comment (too late), but in hindsight, the -t ' ' is not needed and should be removed from the sort command, otherwise it could behave unexpectedly for days of the month 1-9 (since there are 2 spaces in the timestamp in those cases). – James Sneeringer Dec 01 '17 at 15:46
3

If you remember a specific line, you can grep the whole device to find your data back, at the condition that no other data overwrote it. This works for any file.

grep -a -B100 -A100 "command/you remember" /dev/sda1 > /tmp/cron.ressurected

Adjust -B(efore) and -A(fter) to your file size, but 100 lines around should be enough for a cron file. The -a parameter is needed to force grep to consider your device as text.

You will then have to clean the binary mess before and after your data in the resulting file.

And it takes a lot of time. Good luck.

You could also refer to this answer : Undelete / recover deleted files | Unix & Linux Stack Exchange

Hexdump
  • 126
2

I am not sure, it is possible to recover crontab file without backup. But, I am pretty sure you can restore your crontab file from cron logs. As far as I remember, fast every command is listed there with user.