2011-05-13 20 views

Respuesta

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

Puede utilizar id -u wong2 para obtener el UID de un usuario
Usted puede hacer esto con el pitón:

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

A continuación, utilizar el ID de os.chown

+0

Genial ..... ¿qué tal el grupo? – mpen

+0

use 'id -g wong2' – wong2

17

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

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

Cambiar el usuario propietario y/o grupo de la ruta especificada.

usuario puede ser un nombre de usuario del sistema o un uid; lo mismo se aplica al grupo.

Se requiere al menos un argumento.

Disponibilidad: Unix.

2

Dado que la versión shutil admite que group sea opcional, copio y pegué el código en mi proyecto 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

Debe consultar en contra de basestr no? – mpen

+0

@Mark, sí, buena captura! Actualicé el fragmento. – guettli

Cuestiones relacionadas