Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a command as a different user from a root cronjob?

Tags:

I seem to be stuck between an NFS limitation and a Cron limitation.

So I've got root cron (on RHEL5) running a shell script that, among other things, needs to rsync some files over an NFS mount. And the files on the NFS mount are owned by the apache user with mode 700, so only the apache user can run the rsync command -- running as root yields a permission error (NFS being a rare case, apparently, where the root user is not all-powerful?)

When I just want to run the rsync by hand, I can use "sudo -u apache rsync ..." But sudo no workie in cron -- it says "sudo: sorry, you must have a tty to run sudo".

I don't want to run the whole script as apache (i.e. from apache's crontab) because other parts of the script do require root -- it's just that one command that needs to run as apache. And I would really prefer not to change the mode on the files, as that will involve significant changes to other applications.

There's gotta be a way to accomplish "sudo -u apache" from cron??

thanks! rob

like image 423
rob Avatar asked Aug 25 '09 16:08

rob


People also ask

How do I run a cron job as a different user?

Or more simply, you could just run crontab -e when logged in as that user. Alternatively, you could prefix your command in your (root) crontab with sudo -u <username> to run the command as the specified user.

How do I run a command as another user in Unix?

The su command lets you switch the current user to any other user. If you need to run a command as a different (non-root) user, use the –l [username] option to specify the user account.


1 Answers

su --shell=/bin/bash --session-command="/path/to/command -argument=something" username &

Works for me (CentOS)

like image 137
Kitty Avatar answered Sep 23 '22 17:09

Kitty