User sudo to set user and group ownership
14573
def chown(dirs, user=None, group=None):
    """"""
    if isinstance(dirs, basestring):
        dirs = [dirs]
    args = ' '.join(dirs)
    if user and group:
        return sudo('chown {}:{} {}'.format(user, group, args))
    elif user:
        return sudo('chown {} {}'.format(user, args))
    elif group:
        return sudo('chgrp {} {}'.format(group, args))
    else:
        return None
551162
def cli(env, identifier, enable, permission, from_user):
    """"""
    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
    result = False
    if from_user:
        from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
        result = mgr.permissions_from_user(user_id, from_user_id)
    elif enable:
        result = mgr.add_permissions(user_id, permission)
    else:
        result = mgr.remove_permissions(user_id, permission)

    if result:
        click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
    else:
        click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red')
955138
def _compute_am_i_owner(self):
        """"""
        for rec in self:
            rec.am_i_owner = (rec.create_uid == self.env.user)
409656
public function setUserAndGroup()
    {
        // Get uid.
        $user_info = posix_getpwnam($this->user);
        if (!$user_info) {
            static::log("Warning: User {$this->user} not exsits");
            return;
        }
        $uid = $user_info['uid'];
        // Get gid.
        if ($this->group) {
            $group_info = posix_getgrnam($this->group);
            if (!$group_info) {
                static::log("Warning: Group {$this->group} not exsits");
                return;
            }
            $gid = $group_info['gid'];
        } else {
            $gid = $user_info['gid'];
        }

        // Set uid and gid.
        if ($uid != posix_getuid() || $gid != posix_getgid()) {
            if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
                static::log("Warning: change gid or uid fail.");
            }
        }
    }
621015
def ownership(self, ownership):
        
        error_msg = 'ownership must be a list of dictionaries'
        if ownership:
            if not isinstance(ownership, list):
                raise TypeError(error_msg)
            if not all([isinstance(item, dict) for item in ownership]):
                raise TypeError(error_msg)
            if not all([item.get('party_id') for item in ownership]):
                raise ValueError('Ownership missing one or more party_ids')
            if not all([item.get('split') for item in ownership]):
                raise ValueError('Ownership missing one or more splits')
            if sum([item.get('split') for item in ownership]) != Decimal('1'):
                raise ValueError('Ownership must sum up to 100%')
        self._ownership = ownership
335767
def AuthorizeGroup(self, group, subject):
    """"""

    # Add the subject to the dict if is isn't present, so it will get checked in
    # CheckPermissions
    self.authorized_users.setdefault(subject, set())
    self.group_access_manager.AuthorizeGroup(group, subject)
278767
def set_owner(self, path, **kwargs):
        
        response = self._put(path, 'SETOWNER', **kwargs)
        assert not response.content
765647
def put_sudo(data, to)
      filename = File.basename(to)
      to_directory = File.dirname(to)
      put data, "/tmp/#{filename}"
      run "#{sudo} mv /tmp/#{filename} #{to_directory}"
    end
1015364
def groups_remove_owner(self, room_id, user_id, **kwargs):
        """"""
        return self.__call_api_post('groups.removeOwner', roomId=room_id, userId=user_id, kwargs=kwargs)
723039
def add_user_to_group(username, group):
    """"""
    cmd = ['gpasswd', '-a', username, group]
    log("Adding user {} to group {}".format(username, group))
    subprocess.check_call(cmd)
134301
def group_perms_for_user(cls, instance, user, db_session=None):
        
        db_session = get_db_session(db_session, instance)
        perms = resource_permissions_for_users(
            cls.models_proxy,
            ANY_PERMISSION,
            resource_ids=[instance.resource_id],
            user_ids=[user.id],
            db_session=db_session,
        )
        perms = [p for p in perms if p.type == "group"]
        # include all perms if user is the owner of this resource
        groups_dict = dict([(g.id, g) for g in user.groups])
        if instance.owner_group_id in groups_dict:
            perms.append(
                PermissionTuple(
                    user,
                    ALL_PERMISSIONS,
                    "group",
                    groups_dict.get(instance.owner_group_id),
                    instance,
                    True,
                    True,
                )
            )
        return perms
1297923
def owner(self):
        
        """
        if os.name == 'nt':
            if win32security is None:
                raise Exception("path.owner requires win32all to be installed")
            desc = win32security.GetFileSecurity(
                self, win32security.OWNER_SECURITY_INFORMATION)
            sid = desc.GetSecurityDescriptorOwner()
            account, domain, typecode = win32security.LookupAccountSid(None, sid)
            return domain + u'\\' + account
        else:
            if pwd is None:
                raise NotImplementedError("path.owner is not implemented on this platform.")
            st = self.stat()
            return pwd.getpwuid(st.st_uid).pw_name
408478
def _UpdateSudoer(self, user, sudoer=False):
    
    if sudoer:
      self.logger.info('Adding user %s to the Google sudoers group.', user)
      command = self.gpasswd_add_cmd.format(
          user=user, group=self.google_sudoers_group)
    else:
      self.logger.info('Removing user %s from the Google sudoers group.', user)
      command = self.gpasswd_remove_cmd.format(
          user=user, group=self.google_sudoers_group)

    try:
      subprocess.check_call(command.split(' '))
    except subprocess.CalledProcessError as e:
      self.logger.warning('Could not update user %s. %s.', user, str(e))
      return False
    else:
      self.logger.debug('Removed user %s from the Google sudoers group.', user)
      return True
144017
def set_owner
      return unless owner || group
      chown = command? 'chown'

      return unless chown

      cmd = [chown, '-R', "#{owner}:#{group}", destination_path]
      logger.debug { "Running command: #{cmd.join ' '}" }
      system(*cmd)
    end
2116
public void setOwner(String src, String username, String group
  ) throws IOException {
    INode[] inodes = null;
    writeLock();
    try {
      if (isInSafeMode()) {
        throw new SafeModeException("Cannot set permission for " + src, safeMode);
      }
      inodes = dir.getExistingPathINodes(src);
      if (isPermissionCheckingEnabled(inodes)) {
        FSPermissionChecker pc = checkOwner(src, inodes);
        if (!pc.isSuper) {
          if (username != null && !pc.user.equals(username)) {
            if (this.permissionAuditOnly) {
              // do not throw the exception, we would like to only log.
              LOG.warn("PermissionAudit failed on " + src + 
                  ": non-super user cannot change owner.");
            } else {
              throw new AccessControlException("Non-super user cannot change owner.");
            }
          }
          if (group != null && !pc.containsGroup(group)) {
            if (this.permissionAuditOnly) {
              // do not throw the exception, we would like to only log.
              LOG.warn("PermissionAudit failed on " + src + 
                  ": user does not belong to " + group + " .");
            } else {
              throw new AccessControlException("User does not belong to " + group
                  + " .");
            }
          }
        }
      }
      dir.setOwner(src, username, group);
    } finally {
      writeUnlock();
    }
    getEditLog().logSync(false);
    if (auditLog.isInfoEnabled()) {
      logAuditEvent(getCurrentUGI(),
        Server.getRemoteIp(),
        "setOwner", src, null, getLastINode(inodes));
    }
  }
1258136
def share_library(repo_id,user,group_id,permission="rw",share_type="group")
      put_share_library(repo_id,share_type,user,group_id,permission)
    end
956495
private void checkOwner(LockedInodePath inodePath)
      throws AccessControlException, InvalidPathException {
    // collects inodes info on the path
    List<InodeView> inodeList = inodePath.getInodeViewList();

    // collects user and groups
    String user = AuthenticatedClientUser.getClientUser(ServerConfiguration.global());
    List<String> groups = getGroups(user);

    if (isPrivilegedUser(user, groups)) {
      return;
    }

    checkInodeList(user, groups, null, inodePath.getUri().getPath(), inodeList, true);
  }