Search code examples
pythonlinuxrootsudoprivileges

Drop root privileges for certain operations in Python


In my Python script, I perform a few operations that need root privileges. I also create and write to files that I don't want to be owned exclusively by root but by the user who is running my script.

Usually, I run my script using sudo. Is there a way to do the above?


Solution

  • You can switch between uid's using os.seteuid(). This differs from os.setuid() in that you can go back to getting root privileges when you need them.

    For example, run the following as root:

    import os
    
    open('file1', 'wc')
    
    # switch to userid 501
    os.seteuid(501)
    open('file2', 'wc')
    
    # switch back to root
    os.seteuid(0)
    open('file3', 'wc')
    

    This creates file1 and file3 as root, but file2 as the user with uid 501.

    If you want to determine which user is calling your script, sudo sets two environment variables:

    SUDO_USER
    SUDO_UID
    

    Respectively the username and the uid of the user who called sudo. So you could use int(os.environ['SUDO_UID']) to use with os.seteuid().