Tuesday, 8 July 2014

crontab deleted accidently - how to restore it EXPLAINED!

Well, accidents do happen! Usually, when they do happened you are not prepared for them.

One of those accidents in Linux sysadmin world is definitely erasing crontab. You did not have to do it. But you have to restore it!

Ok, few things you need to know first!
1.Crontab is scheduler you users. Every user has it's own crontab. One user can not change crontabs of another user (except if root gave him permission)

# whoami
test
# crontab -e -u test1
must be privileged to use -u


But user can delete it's own crontab. How? Well that is not subject of this post but usually reason is lack of knowledge. By this I think of this

#crontab -r

This will remove your crontab. And you can't do nothing about it. Point is - if you do not know what you are doing then DON'T do it! Read first about it or use some test server,etc.

By the time user calls you to say that his crontab is missing, damage is already done. And they will call you.

2. When any user create crontab, file is generated with that crontab. So, when you edit or list your crontab, you actually reading that file. Depending of your Linux distro, end location may wary but
they are all located in /var/spool/cron/ folder ( on Ubuntu location is /var/spool/cron/crontabs, on Sles11 location is /var/spool/cron/tabs, on Centos location is /var/spool/cron). So when you list this folder you will see something like this

# ls
root  test  test1

This means that users root, test and test1 have crontabs! If you read these files you will see that they are same as crontab that you edit!
Let's delete crontab for user test1!

$ whoami
test1
$ crontab -r
$ crontab -l
no crontab for test1

List
# ls
root  test

And now.... restore of crontab! If you don't have backup of this folder/files/OS, they you can't restore crontab for that perticular user (in are case test1)! If this is the case, then your user has to write down crontab again. This can be a very big problem because at this point all of your scripts that were running throught crontab will not run on that particular time. This is just small example why you (if you are serious about administration) need to have backup!
 
If you do have backup, just restore file to crontab location!

# cp /root/cron123 test1
root@ubuntu:/var/spool/cron/crontabs# ls
root  test  test1
root@ubuntu:/var/spool/cron/crontabs# crontab -l -u test1
* * * * * date


In case that user accuse you that you deleted his crontab file(because root can edit/delete other user crontabs), depending of log level in your system log, you will have notification of crontab actions!

Jul  8 09:20:26 ubuntu crontab[22165]: (test1) LIST (test1)
Jul  8 09:20:36 ubuntu crontab[22167]: (test1) DELETE (test1)
Jul  8 09:20:45 ubuntu crontab[22168]: (test1) LIST (test1)





No comments:

Post a Comment