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

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

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) 

自Python 3.3以来https://docs.python.org/3.3/library/shutil.html#shutil.chown

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

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

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

至less需要一个参数。

可用性:Unix。

由于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) 

你可以用id -u wong2来获取用户的uid
你可以用python来做到这一点:

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

然后使用id到os.chown