如何按名称更改目录的用户和组权限?
Posted
技术标签:
【中文标题】如何按名称更改目录的用户和组权限?【英文标题】:How to change the user and group permissions for a directory, by name? 【发布时间】:2011-08-25 02:08:12 【问题描述】:os.chown 正是我想要的,但我想按名称指定用户和组,而不是 ID(我不知道它们是什么)。我该怎么做?
【问题讨论】:
Python: finding uid/gid for a given username/groupname (for os.chown)的可能重复 【参考方案1】:您可以使用id -u wong2
获取用户的uid
你可以用 python 做到这一点:
import os
def getUidByUname(uname):
return os.popen("id -u %s" % uname).read().strip()
然后用id去os.chown
【讨论】:
【参考方案2】: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
的情况下进行设置吗?
是的,只需根据文档 (docs.python.org/3/library/os.html#os.chown) 为要忽略的 ID 传递 -1【参考方案3】:
自 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。
【讨论】:
【参考方案4】:由于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)
【讨论】:
你应该检查 basestr no 吗?以上是关于如何按名称更改目录的用户和组权限?的主要内容,如果未能解决你的问题,请参考以下文章