64

os.chown正是我想要的,但我想按名称指定用户和组,而不是 ID(我不知道它们是什么)。我怎样才能做到这一点?

4

4 回答 4

119
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)
于 2011-05-13T16:31:27.170 回答
47

从 Python 3.3 https://docs.python.org/3.3/library/shutil.html#shutil.chown

import shutil
shutil.chown(path, user=None, group=None)

更改给定路径的所有者用户和/或组。

user 可以是系统用户名或 uid;这同样适用于组。

至少需要一个参数。

可用性:Unix。

于 2015-01-26T06:53:37.637 回答
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)
于 2015-10-22T13:33:32.070 回答
-3

您可以使用id -u wong2获取用户的 uid
您可以使用 python 执行此操作:

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

然后使用 id 来os.chown

于 2011-05-13T16:25:06.443 回答