sudoers NOPASSWD tag doesn't seem to work

I’m working on adjusting a script I found here for my own purposes.

In essence, the script checks some conditions, and then runs one of two commands using sudo. The command executes as the user cas.

Since the script won’t run interactively, I want to ensure that the sudo commands in there go through without a password prompt. So, I added the following lines to my sudoers file:

ALL     ALL = NOPASSWD: /usr/bin/systemctl mask sleep.target suspend.target
ALL     ALL = NOPASSWD: /usr/bin/systemctl unmask sleep.target suspend.target

From my understanding of how the sudoers file works, this means that all users are allowed to execute the commands /usr/bin/systemctl mask sleep.target suspend.target and /usr/bin/systemctl unmask sleep.target suspend.target without a password prompt.

Instead, the password prompt still appears:

cas-desktop :: ~ » sudo /usr/bin/systemctl mask sleep.target suspend.target
[sudo] password for cas:
sudo: a password is required

I’ve also tried without sudo:

cas-desktop :: ~ » /usr/bin/systemctl mask sleep.target suspend.target
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-unit-files ====
Authentication is required to manage system service or unit files.
Authenticating as: Cas (cas)
Password:

I’m not sure what else to do to make this work, so if you have an idea please do let me know.

Asked By: Cas

||

Please run sudo -l and see if you have other allowed sudo command lines defined for your user. This will display all applicable sudoers configuration lines, both from the main configuration and from any included /etc/sudoers.d/* files, if you have any.

Ordering is important: the last line that can match your command will be honored. If that line is a general (ALL : ALL) ALL line without the NOPASSWD: tag, you will be asked for a password. In that case, move your NOPASSWD:-tagged lines to a later position in the sudoers file.

If the last line of the sudoers file is @includedir /etc/sudoers.d, consider moving your sudo configuration lines into a separate file in /etc/sudoers.d/. Note that any filenames in that directory that either end in ~ or contain a . character will be ignored.


Alternatively, to allow it without sudo, you would need to write a polkit rule file, e.g. /etc/polkit-1/rules.d/01-local-sleep-suspend.rules:

// -*- mode: js2 -*-
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.systemd1.manage-units" &&
         (action.lookup("unit") == "sleep.target" ||
          action.lookup("unit") == "suspend.target") &&
        subject.user == "cas") {
            return polkit.Result.YES;
    }
});
Answered By: telcoM
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.