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

rob picture rob · Aug 25, 2009 · Viewed 33k times · Source

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

Answer

Kitty picture Kitty · Feb 18, 2011

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

Works for me (CentOS)