2011-05-13 97 views
39

os.chown正是我想要的,但我想按名稱指定用戶和組,而不是ID(我不知道它們是什麼)。我怎樣才能做到這一點?如何按名稱更改目錄的用戶和組權限?

+0

的可能重複的[Python的:找到UID/GID對於一個給定的用戶名/組名(對於os.chown)](http://stackoverflow.com/questions/826082/python-finding -uid-gid-for-a-given-username-groupname-for-os-chown) – Louis 2015-04-16 18:08:34

回答

82
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) 
-1

您可以使用id -u wong2獲得用戶的UID
你可以使用Python做到這一點:

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

然後使用id來os.chown

+0

酷.....雖然這個團隊怎麼樣? – mpen 2011-05-13 16:31:20

+0

use'id -g wong2' – wong2 2011-05-13 16:36:47

2

由於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) 
+0

您應該檢查basestr no嗎? – mpen 2015-10-22 13:38:33

+0

@Mark,好的,趕上!我更新了片段。 – guettli 2015-10-22 13:58:19

相關問題