python - 使用 sudo 使用 python 创建文件使其所有者成为 root

标签 python linux file owner

我有一个在 linux 上运行的名为 myCreate.py 的简单 python 脚本:
fo = open("./testFile.txt", "wb")

当我运行 python ./myCreate.py - testFile.txt 的所有者仍然是我的用户。 当我运行 sudo python ./myCreate.py - testFile.txt 的所有者现在是 root。

两次执行之前都没有运行 testFile.txt

我怎样才能让文件的所有者保持真实用户而不是有效用户?! 谢谢!

最佳答案

使用 sudo 运行脚本意味着您以 root 身份运行它。所以您的文件归根用户所有是正常的。

您可以做的是在文件创建后更改其所有权。为此,您需要知道哪个用户运行 sudo。还好有个SUDO_UID使用 sudo 时设置的环境变量。

所以,你可以这样做:

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

然后,您需要change the file ownership :

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 更新了我的答案

关于python - 使用 sudo 使用 python 创建文件使其所有者成为 root,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25791311/

相关文章:

c - 逐字读取文件并输出空格

Python - 将文件写入给定的偏移量

python - 格式化 self,这是一个字典

python内置函数类型,如何为新类型定义成员函数?

linux - LED定时器触发Linux

python - linux/wine/python-os 参数忽略错误

python - 单击鼠标而不移动光标?

python - 回答计算器

php - 以简单的 PHP 形式显示来自两个或多个查询的不同数据

python - 从大文件中提取特定行