Search code examples
pythonlinuxsudosnapcraft

How to launch Linux elevated privileges window from Python?


I am writing a python3 app, running with a GUI (not in the terminal) as the user. While this app is running as the user, I need to also execute a command that requires root privileges. I've seen numerous examples of how to do this in the terminal, like this one, which does in fact work great in the terminal:

import subprocess
subprocess.call('sudo echo "Hello world!"', shell=True)

...but my python app is not running in the terminal, and this method doesn't seem to automatically provoke a visible system prompt when my GUI code calls it.

Other apps, notably the Snap Store, somehow launch what appears to be a system popup when they need to do something with root privileges. For example, when I use the Snap Store to install Notepad++ on Ubuntu, I get this popup, which I suspect is a system popup rather than something the Snap Store folks custom-designed.

Snap Store elevated privileges popup

I'm not super familiar with Linux systems, but I assume this is not a custom popup instead of a system popup because who wants to give their root password to the makers of one of their apps? Instead, users would be giving it to the system (which already knows it), and the 3rd-party app itself doesn't have access to the actual password, but can now run a command as root.

How can I launch an identical popup from my Python app in order to run a command that requires root privileges? Or, alternatively, how else can I run a root command from my python GUI running as the user?

Thanks in advance for any clear assistance you can provide!


Solution

  • Have you tried pkexec?

    Not sure about your GUI but running a simple python script (python3.8, pycharm, ubuntu 18.04) results in the popup you desire (can't do the screen print of the pop-up).

    import os
    
    os.system("pkexec ls -l")