How to create a desktop shortcut that launches a command line program as root without requiring password

I’m trying to create a desktop shortcut that changes my monitor input by executing sudo /usr/bin/ddcutil -d 1 setvcp 60 0xF without requiring a password. I’ve made an entry in the sudoers.d directory and if the command is run from the terminal no password is required as expected, but when I click on the shortcut it prompts for a password. How what needs to be done to make this shortcut run without a password?

.desktop file:

[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=Windows 10
Comment=Switch Display to Windows Virtual Machine
Icon=/usr/share/icons/windows-icon.png
Terminal=true
Exec=sudo /usr/bin/ddcutil -d 1 setvcp 60 0xF

sudoers file:

myusername ALL = NOPASSWD: /usr/bin/ddcutil

The solution here doesn’t work because gksu is deprecated and using pkexec instead as suggested in one of the answers still prompts for a password.

Asked By: ks0ze

||

The solution seems to be using pkexec with a PolicyKit configuration. This answer covers more details on the PolicyKit settings. It is geared towards executing GUI applications without requiring a password but mostly applies to non-graphical applications as well.

For my case, the .desktop file was updated to replace sudo with pkexec. Terminal= can be set to either true or false:

[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=Windows 10
Comment=Switch Display to Windows Virtual Machine
Icon=/usr/share/icons/windows-icon.png
Terminal=false
Exec=pkexec /usr/bin/ddcutil -d 1 setvcp 60 0xF

Then, a PolicyKit entry had to be made at /usr/share/polkit-1/actions/com.ubuntu.pkexec.ddcutil.policy:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
  "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
  "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>

  <action id="com.ubuntu.pkexec.ddcutil">
    <defaults>
      <allow_active>yes</allow_active>
    </defaults>
    <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/ddcutil</annotate>
  </action>

</policyconfig>

/var/log/auth.log seems to be where PolicyKit messages are logged if needed for debugging.

Answered By: ks0ze

made this work by adding the full command to the sudoers file

myusername ALL = NOPASSWD:/usr/bin/ddcutil -d 1 setvcp 60 0xF
Answered By: untitled
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.