12

I have a service in linux called appSevice When I start and stop with these commands, it works:

sudo systemctl start appSevice.service;
sudo systemctl stop  appSevice.service;

But when I try to execute these from JAVA code, for example:

Runtime.getRuntime().exec(new String[]{"systemctl", "stop", "appService.service"});

...it doesn't work and I get this error:

>  Failed to stop appService.service: Interactive authentication required

Here's my service :

[Service]
Type=simple
ExecStart=/opt/soft/v1/launchAppService.ksh start
User=Jms-User
Restart=on-abort

Is there a way to avoid this error and run the service without providing a password?

yoyo
  • 131

2 Answers2

12

There are three ways to do it:

  1. Put appService.service in ~/.config/systemd/system/ and remove the User= line. Then you can control it with:
systemctl --user start appService.service
systemctl --user stop appService.service
  1. Add a polkit rule. I think this question is very close to what you're looking for: systemd start as unprivileged user in a group. If you are on debian/ubuntu (polkit < 106), then this would work:
/etc/polkit-1/localauthority/50-local.d/service-auth.pkla
---
[Allow yourname to start/stop/restart services]
Identity=unix-user:youname
Action=org.freedesktop.systemd1.manage-units
ResultActive=yes

If you are on Arch/Redhat (polkit >= 106), then this would work:

/etc/polkit-1/rules.d/service-auth.rules
---
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.systemd1.manage-units" &&
        subject.user == "yourname") {
        return polkit.Result.YES;
    } });
  1. sudo. I'm not a big fan of this because sudo shouldn't need to rely on a NOPASSWD: configuration and I don't feel that it's designed to be invoked indirectly. That's what polkit is designed for.
/etc/sudoers.d/sysctl
---
youname ALL = NOPASSWD: /bin/systemctl

If this is for software you plan to distribute, I'd definitely go with the polkit solution and do it per group (per the linked answer). It means you don't have to hard-code a username, instead add whichever users you like to that group to get the functionality.

Stewart
  • 13,677
  • For Ubuntu (polkit < 106) I have to add: ResultAny=yes and ResultInactive=yes to service-auth.pkla file – fsbflavio Mar 14 '24 at 14:35
4

Maybe you should create a unit from a user?

systemctl edit --user --force --full myNewUnit

A new file will open in the editor ~/.config/systemd/user/myNewUnit.service Insert content, save and work with it without root rights

systemctl enable --user myNewUnit
systemctl start --user myNewUnit
systemctl status --user myNewUnit

Or if you need to edit than open without --force

systemctl edit --user --full myNewUnit

I hope I haven't messed up anything and it will be useful

nezabudka
  • 2,428
  • 6
  • 15
  • In fact, a temporary file is opened in the editor. During saving its correctness is checked and then the final unit file is created – nezabudka Oct 21 '20 at 12:08