Best Practice to Run Linux Service as a Different User

Best practice to run Linux service as a different user

On Debian we use the start-stop-daemon utility, which handles pid-files, changing the user, putting the daemon into background and much more.

I'm not familiar with RedHat, but the daemon utility that you are already using (which is defined in /etc/init.d/functions, btw.) is mentioned everywhere as the equivalent to start-stop-daemon, so either it can also change the uid of your program, or the way you do it is already the correct one.

If you look around the net, there are several ready-made wrappers that you can use. Some may even be already packaged in RedHat. Have a look at daemonize, for example.

Running services as non root user

The way i solved this way back when, was by having a script that ran every minute from cron. This script then checked to make sure everything i wanted to run was in fact running, and started it if it wasn't.

I probably wouldn't consider this "the best way", but it worked.

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"

How to add user input when starting a service in systemd

I figured it out in such a way:
I created .sh file in usr/bin with this content:

#!/usr/bin/bash
yes | /home/marek/webcash/webminer

Then I created config file in systemd with ExecStart: /path/to/file.sh

and now it works - systemd is running correctly, the logs are logging, the answer "yes" was typed only once in binary file when the user prompt appeared.



Related Topics



Leave a reply



Submit