There are various tools for various desktops that aim to run a graphical application as root. gksudo, kdesudo, empower, etc...

But what if I'm writing a script that could be used on any Linux desktop? Is there an xdg-sudo of some sort..? A standard for getting sudo access in a desktop environment?


Following @Tachyons suggestion, I researched a LOT about pkexec and it is awesome!

  • It is part of PolicyKit, a widely used package.
  • Hosted and sponsored by freedesktop.org
  • Default in Gnome, Unity, MATE, Cinnamon, KDE, LXDE and XFCE, and possibly others
  • Works via D-Bus, so it's completely desktop-neutral, with a well-defined protocol.
  • In many DEs it is used in several services like login screen, shutdown/restart, disk management (udisks/automount) and so on.

So yes, it meets all requirements, and I guess it's the closest thing an "universal gksudo" can be.

That said, pkexecis the command-line front-end to PolicyKit. There are 2 basic modes of operation:

  • Simply run it as you would with sudo, and you get a nice GUI prompt:

    $ pkexec rm -rf /

pkexec GUI prompt

  • Or create a PolicyKit authorization file for you application, drop it in /usr/share/polkit-1/rules.d, and it will allow a great deal of customization and security-related options, for example root access for certain actions only, no need of password for others, access limited to certain paths, etc. You can fine-tune your settings with amazing granularity.

A more general way would be to write a "helper program". Such a program would prompt the user for a password; if you are sure that, say, Zenity, is installed, you can use that, otherwise you'll need to write the helper program in Python or something else that can interact with the GUI.

Read the sudo manual for the -A ("askpass") and -S (stdin) options.

And remember that when you run sudo from your script, you need the -H (home) option to simulate gksudo.

This method works well, but you need to test the helper program thoroughly to ensure that it is bug-free.

  • 1
    You also need to handle xauth token passing in your program - which is not trivial. – symcbean Aug 23 '19 at 13:30

No, there isn't any standard way of getting root (or any other user's) privileges.

If you want to be compatible with as much systems as possible don't assume any way but tell the user that she/he has to run your script as a specific user. Then it's up to the user/admin to configure the system so your script is run in a proper way.

Making some suggestion for how to use the most common authentication systems, like su, sudo and ConsoleKit, would be nice.

  • True for early 2009, but thankfully now polkit (formely PolicyKit) is widespread enough to be considered a standard. – MestreLion May 2 '13 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.