Switch user in a init script?

非 Y 不嫁゛ 提交于 2019-12-03 03:58:22

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
....

For upstart, use:

setuid myuser
exec command args
Johan Nestaas

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!