Execute script from rc.local as user instead of root
84,833
Solution 1
Running sudo su user01
in a script does not mean the following commands are sent to the resultant shell. In fact, it likely means a new shell is spawned as user01, which never exits!
Two things:
- You can execute a command as another user either by passing the
-c 'command...'
argument to su, likesu user01 -c '/etc/init.d/script start'
. - Starting a service that uses /etc/init.d from rc.local isn't the correct thing to do. You want to use enable the service at startup using your distribution tools, like
chkconfig
orupdate-rc.d
. You also don't want jobs in /etc/init.d that shouldn't be started asroot
. The jobs themselves can feel free to fork to another user account, but should be invoked by root.
Solution 2
You could put something in /etc/crontab
and run it @reboot
@reboot username /etc/init.d/script start
Solution 3
You can just run the command through sudo like this:
sudo -H -u user01 /etc/init.d/script start
-H sets the HOME environment variable to that of the user
-u specifies the username to run as
Related videos on Youtube
Author by
Philip
Updated on September 18, 2022Comments
-
Philip almost 2 years
I want to execute a script every time my server start up. The problem is that I need to be a certain user to execute the script, if I try to do it as root it cant find certain packages (such as ruby).
I try to change to xxx user01.
sudo su user01 /etc/init.d/script start
This doesn't work however.
-
Greg Petersen almost 12 yearsPost your init script?
-
Dom almost 12 yearsDo you have some logs ?
-
Mat almost 12 yearsWhy don't you simply use
su
in the rc script? -
Ferdinand Prantl about 11 years
-
-
Jake over 7 yearsor in the user's own crontab file.