Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 command

This generally works as expected on Ubuntu/Debian, but on RHEL the script which is executed as the command hangs.
Is there another way to run the command as another user?
(Note that I can't use lsb init functions as they're not available on RHEL/Centos 5.x.)

like image 473
ddario Avatar asked Jul 30 '13 19:07

ddario


People also ask

How do I run a script without another password?

Using Sudoers File You can also su to another user without requiring a password by making some changes in the sudoers file. In this case, the user (for example aaronk) who will switch to another user account (for example postgres) should be in the sudoers file or in the sudo group to be able to invoke the sudo command.


2 Answers

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" 
like image 169
lagweezle Avatar answered Oct 15 '22 10:10

lagweezle


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 
like image 28
LOAS Avatar answered Oct 15 '22 09:10

LOAS