开发者

Bash init - start service under specific user

I am trying to create an init script in bash (U开发者_Go百科buntu) 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>'"


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


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.


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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜