Tutorial :Is it possible to make a Bash file run as root in crontab? [closed]


I need that Bash file to run periodically, and it must be as root.

Is that possible?

[root@file nutch-0.9]# locate crontab  /etc/crontab  /etc/sysconfig/crontab  /usr/bin/crontab  /usr/share/man/man1/crontab.1.gz  /usr/share/man/man1p/crontab.1p.gz  /usr/share/man/man5/crontab.5.gz  /usr/share/vim/vim71/syntax/crontab.vim  [root@file nutch-0.9]#   


Yes, just add it to the root users' crontab; run the crontab -e command.

The places cron stores its files can be a little bizzare, so use the crontab -e command which will make sure it's in the right place, and I believe it checks the syntax.


You can just do

crontab -e  

as root.


Just specify root as the user for the entry in /etc/crontab:

0 0 *  * *  root  somecommand  

Alternatively you can also add the command to root's personal crontab by using crontab -e as root.


No matter what, you will need to have access to the root user account.

  1. you can add it to the root crontab, as suggested
  2. you can use sudo, as suggested
  3. you can use the setuid bit. The issue with the setuid bit is that it needs to be a compiled program. If it is compiled, you can "chmod 4755" and set the owner of the file to root, and it will run as root. If it is not compiled, you can write a tiny wrapper in C (or any other compiled programming language) that simply calls your script, and setuid on the wrapper, and make sure the wrapper is owned by root.

My advice? Use root crontab. It's what it's there for.

Also, there is no user entry in crontab as suggested by sth...the syntax is:

# .---------------- minute (0 - 59)   # |  .------------- hour (0 - 23)  # |  |  .---------- day of month (1 - 31)  # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...   # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat   # |  |  |  |  |  # *  *  *  *  *  command to be executed  

If you want to enter something in crontab as root, just login to your root account, "crontab -e" and voila...root crontab.


I believe all of the entries in root's crontab run as root. You can just make it invoke a Bash script as the action and it should do what you want.


One way of doing this (via sudo):

  1. You need to set up sudo prilvileges for the account to run without entering in the user credentials
  2. Add "sudo /path/to/command" (without the ") to run the command as root. You can also add parameters to the command.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »