linux里面以指定用户运行命令

一、chroot方式

[root@localhost ~]# chroot --userspec "nginx:nginx" "/" sh -c "whoami"
nginx
[root@localhost ~]# chroot --userspec "kibana:kibana" "/" sh -c "whoami"
kibana

以kibana用户启动kibana示例:

chroot --userspec "kibana:kibana" "/" sh -c "/usr/share/kibana/bin/kibana -c /etc/kibana/kibana.yml" >> /var/log/kibana/kibana.stdout 2>> /var/log/kibana/kibana.stderr &
  # Run the program!

  chroot --userspec "$user":"$group" "$chroot" sh -c "

    cd \"$chdir\"
    exec \"$program\" $args
  " >> /var/log/kibana/kibana.stdout 2>> /var/log/kibana/kibana.stderr &

chroot

二、daemon函数形式

参考https://stackoverflow.com/questions/17956151/how-to-run-a-command-as-a-specific-user-in-an-init-script

On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.

The specific function provided to help with this is daemon. If you are intending to use it to start a daemon-like program, a simple usage would be:

daemon --user=username command

If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"

elasticsearch启动脚本示例:

#
# Source function library.
#
if [ -f /etc/rc.d/init.d/functions ]; then
    . /etc/rc.d/init.d/functions
fi

cd $ES_HOME
echo -n $"Starting $prog: "
# if not running, start it up here, usually something like "daemon $exec"
daemon --user elasticsearch --pidfile $pidfile $exec -p $pidfile -d
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval

转载于:https://www.cnblogs.com/wangqingyong/p/11078603.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值