Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 451
mpen Avatar asked May 13 '11 16:05

mpen


People also ask

How do I change user group and user permissions?

Change file permissions To change file and directory permissions, use the command chmod (change mode). The owner of a file can change the permissions for user ( u ), group ( g ), or others ( o ) by adding ( + ) or subtracting ( - ) the read, write, and execute permissions.

What command is used to change the permissions of a directory?

The chmod command enables you to change the permissions on a file. You must be superuser or the owner of a file or directory to change its permissions.

What is the meaning of chmod 777?

Setting 777 permissions to a file or directory means that it will be readable, writable and executable by all users and may pose a huge security risk.


3 Answers

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)
like image 105
Diego Torres Milano Avatar answered Oct 20 '22 14:10

Diego Torres Milano


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.

like image 26
Oleg Neumyvakin Avatar answered Oct 20 '22 13:10

Oleg Neumyvakin


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)
like image 5
guettli Avatar answered Oct 20 '22 15:10

guettli