linux user to specify which run the command

A, chroot way

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

Kibana user to start kibana example:

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

Two, daemon functional form

referencehttps://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 startup script example:

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

Guess you like

Origin www.cnblogs.com/wangqingyong/p/11078603.html