PDA

View Full Version : SUDO inside Cron Job



Elliot
25th July 2008, 02:13 PM
Hi,

I have a cronjob running as root. It restarts a number of users services every morning. It loads a file which a list of services to be restarted and then goes and restarts them as the designated user.

Like so..

sudo -u $OWNER ./startup.sh

It will sudo to the correct user, and run their startup.sh file to start that users services.

When i login and run this script it works fine, but I can not get it working inside a cron.

Any ideas?

Thanks

rhwood
25th July 2008, 02:24 PM
Does the following work:

sudo -b -u $OWNER ./startup.sh

(-b cause sudo to run in the background--I wonder if you are having problems because cron runs w/o a terminal)

Also: if your script is only modifying files, you may prefer to write the script so that it does not have to be run as the given user, but takes $OWNER as an argument and sets the owner/group of the files correctly after it has done whatever it needs to do

Elliot
25th July 2008, 02:33 PM
Hi,

Thanks for your reply. That did not work. It does actually start a process, it will start it as root if i dont do the sudo, which then means that the user who's it is won't be able to control it. Unless there is some way of changing the owner of a process ID or something like that. It's definatly something with the SUDO as other parts of the script work fine.

Any more ideas?

algej
25th July 2008, 03:07 PM
You didn't say exactly how it was failing (file not found, whatever), but nine times out of ten, when something works from the command line but fails from cron, it's because you've forgotten to set up your environment variables. Cron doesn't perform a login and doesn't read your dotfiles.

You may also try using su - instead of sudo to force loading the users' environment:

su - $OWNER -c "/path/to/startup.sh"

EDIT: use absolute paths

Elliot
25th July 2008, 03:45 PM
Thanks for your reply. When i did it as su it started the services as root. I don't know how I could check the error messages sorry.

Elliot
25th July 2008, 03:46 PM
Oh my bad. Worked fine :D Thanks so much!