如何按名称更改目录的用户和组权限?

68

os.chown 正是我所需要的,但我希望能够按名称指定用户和组,而不是ID(我不知道它们是什么)。我该如何做到这一点呢?


4个回答

125
import pwd
import grp
import os

uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = '/tmp/f.txt'
os.chown(path, uid, gid)

我可以在不提供“gid”情况下设置吗? - alper
1
根据文档(https://docs.python.org/3/library/os.html#os.chown),只需将ID参数传入-1即可忽略该项。 - josh2112

57

5

由于shutil版本支持组是可选的,因此我将代码复制并粘贴到我的Python2项目中。

https://hg.python.org/cpython/file/tip/Lib/shutil.py#l1010

def chown(path, user=None, group=None):
    """Change owner user and group of the given path.

    user and group can be the uid/gid or the user/group names, and in that case,
    they are converted to their respective uid/gid.
    """

    if user is None and group is None:
        raise ValueError("user and/or group must be set")

    _user = user
    _group = group

    # -1 means don't change it
    if user is None:
        _user = -1
    # user can either be an int (the uid) or a string (the system username)
    elif isinstance(user, basestring):
        _user = _get_uid(user)
        if _user is None:
            raise LookupError("no such user: {!r}".format(user))

    if group is None:
        _group = -1
    elif not isinstance(group, int):
        _group = _get_gid(group)
        if _group is None:
            raise LookupError("no such group: {!r}".format(group))

    os.chown(path, _user, _group)

你应该检查基本字符串吧? - mpen

-3

您可以使用id -u wong2来获取用户的UID
您也可以使用Python实现:

import os 
def getUidByUname(uname):
    return os.popen("id -u %s" % uname).read().strip()

然后使用该ID来调用os.chown


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接