Escalating Privilages in Python Script

2.2k Views Asked by At

I am looking for a way to escalate privileges within a python GUI app I'm developing. My desired model is GUFW. I like how you don't have to run the main program as root, but when you do anything "rooty," you have to "unlock" it.

I have a program where I am developing text files that need to be saved either in a user's home directory tree or in a directory in /usr (which need the root elevation).

I don't want to run the program as root, but call for root access when/if I need to save the file to a user different from the user running the program (in this case, root).

I don't want to save it to a temporary locations and revert to a (ba)sh call like:

os.system('gksu cp /tmp/myfile /usr/systemdir/myfile')

I would like to do it all programmatically within Python, if possible. In the future, I might need operations that are not simply creating a file but may need some appending in the middle of the file.

Also, after that save operation is done, I want the privies de-escalated.

Could someone point me to a tutorial or some example code for this endevour?

Regards,

Narnie

1

There are 1 best solutions below

1
On

What you want is PolicyKit - the FreeDesktop spec and software for doing exactly this. http://ubuntuforums.org/showthread.php?t=1359397 is a tutorial and sample code for using this with Python (although not having used PolicyKit personally, I can't speak to how good it is or isn't). Note that for new dbus and glib, you will want to use the GObject introspection (from gi.repository import DBus) instead of the old python-dbus bindings, and this will almost certainly have flow-on changes compared to the sample code.