Switch user to init script?

Here is my Init script, which I have on my Ubuntu workstation. I need to run the command as a different user than root, but I just can't figure out how to do this. sudo -u or su newuser does not work.

script:

 respawn console none start on runlevel [2345] stop on runlevel [06] script su "anotherUser" -c ./myCommand end script 
+7
source share
3 answers

I use this:

 su -l $MUSER -c "myCommand args..." 

Refresh . Since there is interest in this answer, I explain how I use it here.

We run servers as regular Linux users, not root. The username consists of three parts:

service, customer, stage

Thus, we can run several services for several clients in one Linux operating system.

Example: foo_bar_p Service "foo" of the client "bar" and "p" means production

Here is the init script part. Init script can be run as root or as user foo_bar_p:

 # /etc/init.d/foo_bar_p-celeryd # scriptname contains linux username SCRIPT_NAME=`basename "$0"` SYSTEM=${SCRIPT_NAME%*-celeryd} U=`id -nu` if [ ! $U == $SYSTEM ]; then if [ $U == "root" ]; then # use "-l (login)" to delete the environment variables of the calling shell. exec su -l $SYSTEM -c "$0 $@ " fi echo "Script must be run from $SYSTEM or root. You are '$U'" rc_exit 1 fi # OK, now I am foo_bar_p cd . $HOME/.bashrc .... 
+18
source

For an upstart, use:

 setuid myuser exec command args 
+6
source

su is probably a more universal approach, but it is also possible on some common distributions with sudo:

 sudo -u $MUSER $COMMAND $ARGS 

(just re-read your question and donโ€™t understand what doesnโ€™t work for you, but it worked for me in init scripts)

+1
source

All Articles