这个页面有一些代码让我找到了它,http://antonym.org/2005/12/dropping-privileges-in-python.html
我想设置 umask 是完成这项工作所必需的,这是这段代码似乎做的唯一我的尝试没有做的事情(我不确定设置 umask 的真正作用,在将其应用于进程的上下文中)
我把他的例子撕了一点,此外,那个页面是 2005 年的,所以我在这里重新发布我的工作解决方案,
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
# Get the uid/gid from the name
running_uid = pwd.getpwnam(uid_name)[2]
running_gid = grp.getgrnam(gid_name)[2]
# Try setting the new uid/gid
try:
os.setgid(running_gid)
except OSError, e:
logging.error('Could not set effective group id: %s' % e)
exit()
try:
os.setuid(running_uid)
except OSError, e:
logging.error('Could not set effective user id: %s' % e)
exit()
# Ensure a very convervative umask
new_umask = 077
old_umask = os.umask(new_umask)
logging.info('drop_privileges: Old umask: %s, new umask: %s' % \
(oct(old_umask), oct(new_umask)))
final_uid = os.getuid()
final_gid = os.getgid()
logging.info('drop_privileges: running as %s/%s' % \
(pwd.getpwuid(final_uid)[0],
grp.getgrgid(final_gid)[0]))