如何在 Python 中切换用户及其组?

如何在 Python 中切换用户及其组?

如何从这个使用orroot_and_user.py运行的名为的 python 脚本切换到管理员用户帐户?doassudo

#!/usr/bin/env python3
from os import geteuid, seteuid
from subprocess import run
from sys import argv, exit

def touch(fname):
    with open(fname, 'a') as f:
        pass

#run this doas ./root_and_user.py 

if geteuid() == 0:
    touch("1.owned-by-root")
    touch("2.owned-by-root")
    seteuid(1000) 
    touch("1.owned-by-admin-user")
    touch("2.owned-by-admin-user")

我编写了自己的自定义函数,也称为touch()创建空文件。1000是 的 id admin_user。当我使用sudodoas文件运行脚本时1.owned-by-admin-user2.owned-by-admin-user它们已创建,但它们仍然属于该组root- 尽管属于admin_user.我的目标是实现这一目标1.owned-by-admin-user,并且2.owned-by-admin-user不仅属于我admin_user,而且还拥有一个团队admin_user。我怎样才能做到这一点?

答案1

os.chown()方法可用于修改 Python 脚本生成的文件的组所有权。尝试这个:

#!/usr/bin/env python3
import os
from os import geteuid, seteuid
from subprocess import run
from sys import argv, exit

def touch(fname):
    with open(fname, 'a'):
        os.utime(fname, None)

#run this doas ./root_and_user.py 

if geteuid() == 0:
    touch("1.owned-by-root")
    touch("2.owned-by-root")
    seteuid(1000) 
    os.chown("1.owned-by-root", 1000, 1000) # change owner and group to admin_user
    os.chown("2.owned-by-root", 1000, 1000) # change owner and group to admin_user
    touch("1.owned-by-admin-user")
    touch("2.owned-by-admin-user")
    seteuid(0)
    os.chown("1.owned-by-admin-user", 1000, 1000) # change owner and group to admin_user
    os.chown("2.owned-by-dmin-user", 1000, 1000) # change owner and group to admin_user

相关内容