8

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

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

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

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

4

3 回答 3

8

使用 sudo 运行脚本意味着您以 root 身份运行它。所以你的文件归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 更新了我的答案

于 2014-09-11T15:55:44.823 回答
2

使用os.chown(), usingos.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']))
于 2014-09-11T15:43:18.700 回答
2

如何使用os.stat首先获取包含文件夹的权限,然后将它们应用于文件创建后。

这看起来像(使用python2):

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 所指出的,如果您要同时创建多个文件,那么将其结构为一个函数会更好。

于 2014-09-11T15:36:53.447 回答