在初始化脚本中切换用户? [英] Switch user in a init script?
问题描述
这是我在Ubuntu工作站上拥有的Init脚本.我需要以root用户以外的其他用户身份运行命令,但是我只是无法理解应该如何执行. sudo -u
或su newuser
似乎都不起作用.
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.
脚本:
respawn
console none
start on runlevel [2345]
stop on runlevel [06]
script
su "anotherUser" -c ./myCommand
end script
推荐答案
我使用这个:
su -l $MUSER -c "myCommand args..."
更新:由于对此答案很感兴趣,因此我在这里解释了使用它的方式.
Update: Since there is interest in this answer, I explain the way I use it here.
我们以普通linux用户而不是root用户的身份运行服务器.用户名包含三个部分:
We run servers as normal linux users, not root. The username contains three parts:
服务,客户,阶段
这样,我们可以在一个Linux操作系统中为多个客户运行多种服务.
This way we can run several services for several customers in one linux OS.
示例:foo_bar_p客户"bar"的服务"foo","p"表示生产
Example: foo_bar_p Service "foo" of customer "bar" and "p" means production
这是初始化脚本的一部分.初始化脚本可以以root或foo_bar_p用户身份执行:
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
....
这篇关于在初始化脚本中切换用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!