How to run SUDO... commands in cronjobs in Ubuntu 16.04?
Solution 1
Simply run crontab -e
as root user . This would run your command with root permission and there is no need to add sudo
before it .
However you can't login with root user and you need to perform your job as cron job you should specified full path in cron file :
$ * * * * * /usr/bin/sudo /your/command
Also you can add NOPASSWD
in front of your command in /etc/sudoers
file to run command as root but without password .
Solution 2
Another option is to put it in the system-wide crontab at /etc/crontab
(or in a file in /etc/cron.d
), where you can specify the user each task is run at:
* * * * * root mkdir /foo/bar
Related videos on Youtube
Shy
Updated on September 18, 2022Comments
-
Shy over 1 year
There are certain terminal commands which can only be run as a root user. If we try to execute them without
sudo
keyword, they fail with thePermission denied
error. An example would be a command to make a directory/folder in certain locations.I need to run one such command as a part of a cron job in my Ubuntu 16.04. Normally I could run the command with the
sudo
keyword in the terminal and I would be prompted to enter the root user's password and then the command would be executed successfully.But now that I have to enter this command as a part of a cron job in my
crontab
file, how do I do this? How do I run such a command as a part of a cronjob?-
Pilot6 over 6 years
cron
runs with root. You don't need to add sudo. -
steeldriver over 6 yearsUsually, one would put such jobs in root's crontab (
sudo crontab -e
rather than plaincrontab -e
) or use the system cron file/etc/crontab
directly. Is there some particular reason you need to use a user crontab? -
George Udosen over 6 years@steeldriver please what's the difference between
sudo crontab -e
andcrontab -e
? -
steeldriver over 6 years@George
sudo crontab -e
inserts the command into root's crontab file/var/spool/cron/crontabs/root
, whereascrontab -e
inserts it into$USER
's crontab file/var/spool/cron/crontabs/$USER
-
George Udosen over 6 years@steeldriver I guess my hunch was right!
-
Sopalajo de Arrierez about 6 yearsI don't think CRON runs as root, @Pilot6 . If you add
* * * * * echo "hello" > /tmp/test.txt
to CronTab as normal user, the newly created file will have your username's owner, group and permissions. -
Pilot6 about 6 yearsYou can't add anything to crontab "as normal user".
-
-
fkraiem over 6 yearsThere is no need for
sudo
since the task will run as root already. -
Ali Ghasempour over 6 years@fkraiem As i said if you don't have access to root account for making new cron as root , you can use sudo .
-
fkraiem over 6 yearsIf you have access to
sudo
, you typically have access to root.