Home » Linux » How to run the cron job as a user instead of root user [closed]

How to run the cron job as a user instead of root user [closed]

Posted by: admin January 30, 2018 Leave a comment

Questions:

I have few bash scripts which are adding to cron jobs with specified timing, but it needs to be executed as root user. I am trying to run those scripts i.e., crob jobs but it needs root user permission, since I am running this jobs in ubuntu ec2 instance where root user is restricted. What would be the work around to run those scripts as root user.

Thanks

Answers:

There are several possibilities:

1) add the script(s) to the crontab of root. To do this you have to do sudo su - or su - to become root, then add the cron jobs by using crontab -e

2) allow a non-root user to use a crontab, and add the cron job to that user’s crontab , by using crontab -e
and set the set-uid flag of your script and change ownership to root, so it will execute as root chmod +s scriptname; chown root scriptname

Questions:
Answers:

You can make a script execute as root by using the setuid flag, which makes a script run as its owner:

chmod +s yourscript
chown root yourscript

Just make yourscript run whatever command you want to run as root.

Note that with this method, any user can run the script.

Questions:
Answers:

Basile is right with his comment. If you want to run something as root in Ubuntu, use sudo.

If you want to execute a script (or some commands) automatically with superuser rights without having to type in a password, run

sudo visudo

to edit the sudoers file. To make sudo stop asking for a password for a specific script (or command) insert

username ALL = NOPASSWD: /path/to/script

where username is the name of the user calling sudo.