使用sudo创建的Python文件归root所有

10 投票
3 回答
9599 浏览
提问于 2025-04-21 03:06

我有一个简单的Python脚本,叫做myCreate.py,在Linux上运行:
fo = open("./testFile.txt", "wb")

当我用命令python ./myCreate.py运行时,testFile.txt的文件拥有者是我的用户。

但是当我用命令sudo python ./myCreate.py运行时,testFile.txt的文件拥有者变成了root。

在这两次执行之前,testFile.txt这个文件并不存在。

我该如何让文件的拥有者保持为真实用户,而不是有效用户呢?谢谢!

3 个回答

2

可以先用 os.stat 来获取包含文件的文件夹的权限,然后在创建文件后把这些权限应用到新文件上。

用 Python 2 的话,代码大概是这样的:

import os

path = os.getcwd()
statinfo = os.stat(path)

fo = open("./testFile.txt", "wb")
fo.close()
euid = os.geteuid()
if (euid == 0) # Check if ran as root, and set appropriate permissioning afterwards to avoid root ownership
    os.chown('./testFile.txt', statinfo.st_uid, statinfo.st_gid)

正如 Elliot 所说,如果你要同时创建多个文件,最好把这个过程写成一个函数,这样结构会更清晰。

2

使用 os.chown() 这个函数,并通过 os.environ 来找到合适的用户 ID:

import os

fo = open("./testFile.txt", "wb")
fo.close()
os.chown('./testFile.txt',
         int(os.environ['SUDO_UID']),
         int(os.environ['SUDO_GID']))
10

用sudo运行你的脚本意味着你是以超级管理员的身份在运行它。所以,你的文件被root(超级管理员)拥有是正常的。

你可以在文件创建后,改变这个文件的拥有者。为了做到这一点,你需要知道哪个用户在使用sudo。幸运的是,有一个叫做 SUDO_UID 的环境变量,它会在你使用sudo时被设置。

所以,你可以这样做:

import os
print(os.environ.get('SUDO_UID'))

然后,你需要 改变文件的拥有者

os.chown("path/to/file", uid, gid)

如果我们把这些放在一起:

import os

uid = int(os.environ.get('SUDO_UID'))
gid = int(os.environ.get('SUDO_GID'))

os.chown("path/to/file", uid, gid)

当然,你会想把它做成一个函数,因为这样更方便,所以:

import os

def fix_ownership(path):
    """Change the owner of the file to SUDO_UID"""

    uid = os.environ.get('SUDO_UID')
    gid = os.environ.get('SUDO_GID')
    if uid is not None:
        os.chown(path, int(uid), int(gid))

def get_file(path, mode="a+"):
    """Create a file if it does not exists, fix ownership and return it open"""

    # first, create the file and close it immediatly
    open(path, 'a').close()

    # then fix the ownership
    fix_ownership(path)

    # open the file and return it
    return open(path, mode)

使用方法:

# If you just want to fix the ownership of a file without opening it
fix_ownership("myfile.txt")

# if you want to create a file with the correct rights
myfile = get_file(path)

编辑:感谢@Basilevs, @Robᵩ 和 @5gon12eder 更新了我的回答

撰写回答