Skip to content
Advertisement

Change ownership and permission without terminal – Python

I have a gui made in glade and am stuck on one thing.

I have a button that changes the ownership and permissions; it works fine except for folders and files owned by root.

Is there anyway of invoking root privilages to run this command without having to input the root password in terminal? i.e. either predefine it within the script or activate a popup promt for the password and impliment it.

Example of the code below:

def on_button_clicked(self, widget):
    path = {defined from combobox}
    os.chdir(path)

    uid = os.getuid()
    gid = os.getgid()

    for root, dirs, files in os.walk(path):
        for d in dirs:
            os.chown(os.path.join(root, d), uid, gid)
            os.chmod(os.path.join(root, d), 0o755)
        for f in files:
            os.chown(os.path.join(root, f), uid, gid)
            os.chmod(os.path.join(root, f), 0o755)

Advertisement

Answer

The prize goes to @intepidhero for proviving some useful links; the first one did the trick!

All you have to do is make sure that your user/group is in sudoers and put the folling code in the head of your script, and hey presto … you are running your app elevated to sudo!

import os
import sys

euid = os.geteuid()
if euid != 0:
    print "Script not started as root. Running sudo.."
    args = ['sudo', sys.executable] + sys.argv + [os.environ]
    # the next line replaces the currently-running process with the sudo
    os.execlpe('sudo', *args)

print 'Running. Your euid is', euid
Advertisement