Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch user in a init script?

Tags:

sudo

init

ubuntu

Here's my Init script which I have at my Ubuntu workstation. I need to run a command as another user than root, but I just can't get my head around how it should be done. Neither sudo -u or su newuser seems to work.

The script:

respawn
console none

start on runlevel [2345]
stop on runlevel [06]

script
  su "anotherUser" -c ./myCommand
end script
like image 946
Industrial Avatar asked Jan 20 '12 11:01

Industrial


People also ask

How do I switch users in Linux script?

Using su su is a command-line tool that is commonly used to switch users in Linux. Additionally, it also allows us to execute scripts or commands as another user.


3 Answers

I use this:

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

Update: Since there is interest in this answer, I explain the way I use it here.

We run servers as normal linux users, not root. The username contains three parts:

service, customer, stage

This way we can run several services for several customers in one linux OS.

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

Here is the part of the init script. The init script can be executed as root or as foo_bar_p user:

# /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
....
like image 131
guettli Avatar answered Oct 03 '22 16:10

guettli


For upstart, use:

setuid myuser
exec command args
like image 34
Henrik Avatar answered Oct 03 '22 18:10

Henrik


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

sudo -u $MUSER $COMMAND $ARGS

(just reread your question and didn't realize that doesn't work for you, but it has worked for me in init scripts)

like image 21
Johan Nestaas Avatar answered Oct 03 '22 17:10

Johan Nestaas