How to run a command as a specific user in an init script?

后端 未结 6 2031
南方客
南方客 2020-12-29 03:26

I\'m writing an init script which is supposed to execute a single command as a user different than root. This is how I\'m doing it currently:
sudo -u username comm

相关标签:
6条回答
  • 2020-12-29 03:40

    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"
    
    0 讨论(0)
  • 2020-12-29 03:42

    Adding this answer as I had to lookup multiple places to achieve my use case. I had a script that runs on startup. This script runs process as a specific (passwordless) user and is running on multiple linux flavors. Here are options on different flavors: (I have taken java as target process for example)

    1. RHEL / CentOS 6:

    source /etc/rc.d/init.d/functions
    daemon --user=myUser $JAVA_HOME/bin/java
    

    2. RHEL 7 / SUSE12 / other linux flavors where systemd is used:

    In your systemd unit file add:

    User=myUser
    

    3. Suse 11:

    /sbin/startproc -u myUser $JAVA_HOME/bin/java

    0 讨论(0)
  • 2020-12-29 03:51

    For systemd style init scripts it's really easy. You just add a User= in the [Service] section.

    Here is an init script I use for qbittorrent-nox on CentOS 7:

    [Unit]
    Description=qbittorrent torrent server
    
    [Service]
    User=<username>
    ExecStart=/usr/bin/qbittorrent-nox
    Restart=on-abort
    
    [Install]
    WantedBy=multi-user.target
    
    0 讨论(0)
  • 2020-12-29 03:52

    Instead of sudo, try

    su - username command
    

    In my experience, sudo is not always available on RHEL systems, but su is, because su is part of the coreutils package whereas sudo is in the sudo package.

    0 讨论(0)
  • 2020-12-29 04:01

    I usually do it the way that you are doing it (i.e. sudo -u username command). But, there is also the 'djb' way to run a daemon with privileges of another user. See: http://thedjbway.b0llix.net/daemontools/uidgid.html

    0 讨论(0)
  • 2020-12-29 04:03

    If you have start-stop-daemon

    start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
    
    0 讨论(0)
提交回复
热议问题