I am writing a gui program using wx module in python. In program whenever I am accessing a folder which requires root privilege then it asks password at terminal but I want to display the dialog to user to enter the password and authenticate him. How to call that dialog and authenticate the user in ubuntu?

  • You write that it "asks password at terminal" does that mean that you are calling sudo terminal commands from python?
    – TLE
    May 17 '12 at 20:10
  • I think it's likely you should use PolicyKit rather than sudo, but I don't have enough knowledge of Python or PolicyKit to write a good answer explaining how. Perhaps someone else can. May 24 '12 at 5:32
  • How are you going to use this ? just executing a command
    – daisy
    May 27 '12 at 4:45

There are two different Q&As at stackoverflow answering your question: here and here.

Both answers use the command gksudo (already mentioned by @khamer). If you run gksudo command (also without python) it will basically do what sudo does, but with a graphical interface - i.e. ask the user for a password and then run the command as root if the user is in the sudoers file.

To implement the suggested solution from the linked answers in python, you can use something as shown by the following example:

Create a file run.py:


import subprocess
subprocess.call(['gksudo','python create.py'])

And a file create.py:


# Create test file..
f = file("mytestfile", "w")

Then run python run.py and after you enter your password a file owned by root will be created. If you run python create.py it will be owned by you (the file should not exist before running the script).


While I'm sure there's a fancier python solution, the down and dirty version is to use gksudo. gksudo does the same thing sudo does, except it creates that dialog for authentication you mentioned instead of asking on the command line.

See https://help.ubuntu.com/community/RootSudo#Graphical_sudo

  • Since this is a question about programming for Ubuntu in Python, can you give a code example showing how to use gksu/gksudo in a Python program? May 26 '12 at 14:52
  • @EliahKagan I wrote an answer with an example which hopefully meets your demands! :)
    – lumbric
    May 29 '12 at 21:27

Insert this script in your code:

import os

Password = raw_input('Please enter your root password!')

sudo_command = '<your command>'

execute = os.system('echo %s|sudo -S %s' % (Password, sudo_command))

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.