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
Is It Ok to Use the Same Input File as Output of a Piped Command
How to Execute a Remote Command Over Ssh with Arguments
How to Check If a Program Is Run in Bash on Ubuntu on Windows and Not Just Plain Ubuntu
How to Run a Script on Login in *Nix
Is There an Invalid Pthread_T Id
Linux: Command to Open Url in Default Browser
How Does Docker Run a Linux Kernel Under MACos Host
Linux: Find All Symlinks of a Given 'Original' File? (Reverse 'Readlink')
Bluetooth Le Signal Strength Linux
How to Sort a File, Based on Its Numerical Values for a Field
How to Prepend a String to the Beginning of Each Line in a File
Linux Command to Check If a Shell Script Is Running or Not
Getting Pid and Details for Topmost Window
Variable in Bash Script That Keeps It Value from the Last Time Running
Tar a Directory, But Don't Store Full Absolute Paths in the Archive