这比你想象的要难。首先,Python提供了^{}和{a2}来更改正在运行的脚本的当前用户/组,您可以创建一个上下文管理器来为您进行竞价,并自动恢复到当前执行的用户:import os
class UnixUser(object):
def __init__(self, uid, gid=None):
self.uid = uid
self.gid = gid
def __enter__(self):
self.cache = os.getuid(), os.getgid() # cache the current UID and GID
if self.gid is not None: # GID change requested as well
os.setgid(self.gid)
os.setuid(self.uid) # set the UID for the code within the `with` block
def __exit__(self, exc_type, exc_val, exc_tb):
# optionally, deal with the exception
os.setuid(self.cache[0]) # revert back to the original UID
os.setgid(self.cache[1]) # revert back to the original GID
为了测试它:
^{pr2}$
您甚至可以创建一个简洁的decorator来选择某些函数应该始终作为另一个用户执行:def as_unix_user(uid, gid=None): # optional group
def wrapper(func):
def wrapped(*args, **kwargs):
with UnixUser(uid, gid):
return func(*args, **kwargs) # execute the function
return wrapped
return wrapper
def test1():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
@as_unix_user(105)
def test2():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
test1() # executes as the current user
test2() # executes as the user with UID: 105
踢皮球的?除了不具有线程安全性之外,它只在当前用户和您要作为其执行函数的用户同时具有^{}和可选的^{}功能时才有效。在
只有一个具有这些功能的用户运行主脚本,然后在必要时进行fork,只在分叉进程上更改UID/GID,这样就可以避免这种情况:import os
def as_unix_user(uid, gid=None): # optional group
def wrapper(func):
def wrapped(*args, **kwargs):
pid = os.fork()
if pid == 0: # we're in the forked process
if gid is not None: # GID change requested as well
os.setgid(gid)
os.setuid(uid) # set the UID for the code within the `with` block
func(*args, **kwargs) # execute the function
os._exit(0) # exit the child process
return wrapped
return wrapper
def test1():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
@as_unix_user(105)
def test2():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
test1() # executes as the current user
test2() # executes as the user with UID: 105
这里的踢球者?您不能从forked函数获取返回数据。如果您需要它,您必须通过管道将它传回父进程,然后在父进程中等待它完成。您还需要选择一种在进程之间传递数据的格式(如果足够简单,我建议使用JSON或使用nativepickle)。。。在
{你已经做了一半的函数了。如果你为了达到你想要的结果而不得不经历这样的磨难,那么很可能是你最初的设计出了问题。在您的例子中,为什么不直接向当前用户提供访问数据库的权限?用户需要有能力切换到另一个可以切换的用户,这样你就不会从中获得任何安全性方面的东西-你只会让你的生活复杂化。在