-->

Drop root privileges for certain operations in Pyt

2020-07-06 03:27发布

问题:

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?

回答1:

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().



回答2:

http://linux.die.net/man/8/sudo quote:
The real and effective uid and gid are set to match those of the target user

So, your only option of knowing which user to use is to read the target user from either a config file or a cmdline option, or someway of heuristical guessing.

A good idea is the so called rights shedding: Start with root privilegs, then do what you nedd them for. Then become a less privileged user.
You would use the os module for that: http://docs.python.org/2/library/os.html#os.setuid



回答3:

I found that using os.seteuid and os.setegid didn't actually drop the root privileges. After calling them I was still able to do things that required root privileges. The solution I found that worked was to use os.setresuid and os.setresgid instead:

sudo_uid = int(os.getenv("SUDO_UID"))
sudo_gid = int(os.getenv("SUDO_GID"))

# drop root privileges
os.setresgid(sudo_gid, sudo_gid, -1)
os.setresuid(sudo_uid, sudo_uid, -1)

subprocess.call("mkdir /foo1", shell = True) # should fail

# regain root privileges
os.setresgid(0, 0, -1)
os.setresuid(0, 0, -1)

subprocess.call("mkdir /foo2", shell = True) # should succeed