How to execute os.* methods as root?

10,283

Solution 1

gnibbler gave a hint at os.chown. The problem was then to know the ID of the user behind sudo. That information is stored in environment variables SUDO_*:

os.chown, (some_path, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))

Splitting the code in 3 files could be a solution, but the code is already mixed, so that's not suitable.

Solution 2

Maybe you can put (2) in a separate script, say script2.py, and in the main script you call sudo script2.py with a popen ?

This way only (2) will be executed as root.

Solution 3

yourscript.py:

run_part_1()
subprocess.call(['sudo', sys.executable, 'part2.py'])
run_part_3()

part2.py:

run_part_2()

Solution 4

You should execute your script as root and do the proper changes to permissions for (3) using os.chmod and os.chown.

It would be possible for you to execute another script with root rights through sudo, but that would also require storing your user's password in the script to pass in to sudo, which is a terrible idea from a security standpoint.

Thus, your issue is about getting the correct permissions on some files/folders. First, pass in or hard code the UID/username of your regular user. Then use os.chown to change the owner, and os.chmod to change the permissions. There are also alternate chown/chmod methods in the os package you should look at: http://docs.python.org/library/os.html

One final note: You don't have to worry about the permissions of symlinks. They have the permissions of what they point to.

Share:
10,283
culebrón
Author by

culebrón

My GitHub profile, my CV at careers. Erde: hiking-light geospatial toolkit I'm a Python & Javascript programmer, know some DBs well. Know some Linux stuff. I speak Russian, Italian, Spanish and English fluently. I'm fond of cycling, MTB orienteering, travelling.

Updated on August 20, 2022

Comments

  • culebrón
    culebrón about 1 year

    Is it possible to ask for a root pw without storing in in my script memory and to run some of os.* commands as root?

    My script

    1. scans some folders and files to check if it can do the job
    2. makes some changes in /etc/...
    3. creates a folder and files that should be owned by the user who ran the script

    (1) can be done as a normal user. I can do (2) by sudoing the script, but then the folder and files in (3) will be root's.

    The issue is that I use a lot of os.makedirs, os.symlink, etc, which stops me from making it runnable by a normal user.

    Tanks 2 all for suggestions

    The solution so far is:

    # do all in sudo
    os.chown(folder, int(os.getenv('SUDO_UID')), int(os.getenv('SUDO_GID')))
    

    thanks to gnibbler for hint.