How to start a service at boot time in ubuntu 12.04, run as a different user?
A basic script to start a service could look like this:
#!/bin/sh
# This is for the 'update-rc.d', so it knows when to start your service.
### BEGIN INIT INFO
# Provides: your-script
# Required-Start: $all
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: a short description
# Description: a long description
### END INIT INFO
COMMAND="echo -n 'I am: '; whoami"
log () {
echo "$@"
logger -p user.info -t "ClueReleaseManager [$$]" "$@"
}
main () {
case "$1" in
stop)
# stop your service
echo "Stopping"
;;
start)
# run your service as user pypi
# doesn't need password as root
echo "Starting"
# you probably want to start it in background
# (don't block the other services)
(su - pypi -c "$COMMAND") &
;;
restart|force-reload)
# restart your service
echo "Restarting"
;;
*)
# wrong command
echo "Unknown command: '$1'"
;;
esac
}
# If you want, you can even log the whole.
# Unless you changed it it should go to /var/log/syslog
main "$1" 2>&1 | log
# Better exit with success, not sure if this can screw up Ubuntus boot process.
exit 0
update-rc.d how-to: Put it in /etc/init.d/your-script (or link to it). Make executable, and add to init services:
$ sudo chmod +x /etc/init.d/your-script
$ sudo update-rc.d your-script defaults
Now you can start and stop your service:
$ sudo your-script start
$ sudo your-script stop
Related videos on Youtube
Alex
Updated on September 18, 2022Comments
-
Alex over 1 year
I have a server ClueReleaseManager which I have installed on a Ubuntu 12.04 system from a separate user (named
pypi
), and I want to be able to start this server at startup.I already have tried to create a simple bash script with some commands (login as user
pypi
, use a virtual python environment, start the server), but this does not work properly. Either the terminal crashes or when I try to ask the status of the service it is started and I am logged in as userpypi
...?So, here the question: What are the steps to take to make sure the ClueReleaseManager service properly starts up on boot time, and which I can control (start/stop/..) during runtime, while the service is running from a user
pypi
?Additional information and constraints:
- I want to do this as simple as possible
- Without any other packages/programs to be installed
- I am not familiar with the Ubuntu 12.04 init structure
- All the information I found on the web is very sparse, confusing, incorrect or does not apply to my case of running a service as a different user from
root
.