How to change the user and group permissions for a directory, by name?

PythonOperating SystemChown

Python Problem Overview


os.chown is exactly what I want, but I want to specify the user and group by name, not ID (I don't know what they are). How can I do that?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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

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

Change owner user and/or group of the given path.

user can be a system user name or a uid; the same applies to group.

At least one argument is required.

Availability: Unix.

Solution 3 - Python

Since the shutil version supports group being optional, I copy and pasted the code to my Python2 project.

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)

Solution 4 - Python

You can use id -u wong2 to get the uid of a user
You can do this with python:

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

Then use the id to os.chown

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmpenView Question on Stackoverflow
Solution 1 - PythonDiego Torres MilanoView Answer on Stackoverflow
Solution 2 - PythonOleg NeumyvakinView Answer on Stackoverflow
Solution 3 - PythonguettliView Answer on Stackoverflow
Solution 4 - Pythonwong2View Answer on Stackoverflow