1. Create a systemd service
Suppose that we have a script in /usr/bin/myscript.sh Also suppose that there is a Linux user named myuser in group ourgroup Now this is the main part of the story in which we make a file in /etc/systemd/system/myservice.service including below directives:
1 2 3 4 5 6 7 8 9 10 11 |
[Unit] Description=Run myscript service as user myuser SyslogIdentifier=myscript [Service] Type=simple User=myuser Group=ourgroup ExecStart=/bin/bash /usr/bin/myscript.sh [Install] WantedBy=multi-user.target |
1 |
$sudo systemctl daemon-reload |
1 2 3 |
$sudo systemctl status myservice $sudo systemctl start myservice $sudo systemctl stop myservice |
2. Use PolicyKit to allow non-root users to mange the service
PolicyKit is an application-level toolkit for defining and handling the policy. As a practical step here we create a new file in /etc/polkit-1/rules.d/99-ourgroup.rules including:
1 2 3 4 5 6 7 8 |
polkit.addRule(function(action, subject) { if (action.id == "org.freedesktop.systemd1.manage-units" && action.lookup("unit") == "myservice.service") && subject.isInGroup("ourgroup")) { return polkit.Result.YES; } }) |
3. Define needed sudoer access using visudo
Linux and Unix administrators use sudoers file to allocate system rights to system users. This allows the administrator to control who does what. Visudo command is a secure and safe way of editing the /etc/sudoers file on Linux. So just run
1 2 3 4 |
%ourgroup ALL= NOPASSWD: /usr/bin/systemctl restart myservice.service %ourgroup ALL= NOPASSWD: /usr/bin/systemctl stop myservice.service %ourgroup ALL= NOPASSWD: /usr/bin/systemctl start myservice.service %ourgroup ALL= NOPASSWD: /usr/bin/systemctl status myservice.servicee |