Bash init - start service under specific user

56,803

Solution 1

Ubuntu uses start-stop-daemon which already supports this feature.

Use the skeleton file from /etc/init.d:

sudo cp /etc/init.d/skeleton /etc/init.d/mynewservice

Edit mynewservice appropriately.

Add the following parameter to the lines that call start-stop-daemon:

--chuid username:group

Example:

Change

start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \

to

start-stop-daemon --start --quiet --chuid someuser:somegroup --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \

Finally, register your service and start it:

update-rc.d mynewservice defaults 99 && service mynewservice start

More info about other options for start-stop-daemon here

Solution 2

Alternatively, you can use the daemon function defined in your /etc/init.d/functions file:

daemon --user=<user> $DIR/program

If you look into its syntax you can do other things like defining PID file location, setting nice level, and whatnot. It's otherwise really useful for starting up services as daemons. Services started up with daemon can easily be terminated by another functions function, killproc.

Solution 3

You can create a script under /etc/init.d/ say your_service_name, with minimal contents

#!/bin/sh
su - <user> -c "bash -c 'cd $DIR ;<service name>'"

Provide appropriate permission to the script. Now use update-rc.d command in the required /etc/rc<run_level>.d directory to create a soft link for your script so that the script is run when system starts with the mentioned run level.
Please refer scripts under /etc/init.d/ for reference & please go through /etc/init.d/README for more details regarding writing the script. Man page for update-rc.d will also help to find out about the usage of update-rc.d. This definitely works on Ubuntu machine I use, but I'm guessing that this facility will be available across distros.
Hope this helps!

Solution 4

I had the same issue and I solved it by

  1. Create bash script and put it in /etc/init.d/ using following pattern
    #!/bin/bash
    su <user> -c "bash -c '<path to service> $1'"

  2. Setup run codes for the script using the following command
    sudo update-rc.d <my_scrpit> defaults

Once this script is set in run codes, upon restarting, root run the script and will pass start/stop to the script as $1, depending on the status of the run mode.
If you want to test your script without restarting you should run it as root and pass the service action e.g. start/stop/restart....
root# ./etc/init.d/my_scrpit start

Share:
56,803
David Ryder
Author by

David Ryder

Devout programmer. Ok designer. Contact me @ http://libryder.com

Updated on July 31, 2020

Comments

  • David Ryder
    David Ryder almost 4 years

    I am trying to create an init script in bash (Ubuntu) that starts a service under a specific user.

    Is there a better way to do that other than this?

    su - <user>  -c "bash -c  'cd $DIR ;<service name>'"