Change the group of a file

    path
        path to the file or directory

    group
        group owner

    CLI Example:

    .. code-block:: bash

        salt '*' file.chgrp /etc/passwd root
489276
def chgrp(path, group):
    '''
    
    '''
    path = os.path.expanduser(path)

    user = get_user(path)
    return chown(path, user, group)
347919
def find_paths_with_suid_sgid(root_path):
    
    cmd = ['find', root_path, '-perm', '-4000', '-o', '-perm', '-2000',
           '-type', 'f', '!', '-path', '/proc/*', '-print']

    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, _ = p.communicate()
    return set(out.split('\n'))
267950
def _salt_to_os_path(path):
    '''
    
    '''
    return os.path.normpath(path.replace(posixpath.sep, os.path.sep))
1368105
public static function setPermissions(string $path, int $mode = null)
    {
        $is_dir = is_dir($path);

        $current_uid = posix_getuid();
        $owner = @fileowner($path);
        if ($current_uid !== $owner)
            return;

        if (self::$file_group)
        {
            $current_gid = filegroup($path);
            $grpinfo = posix_getgrnam(self::$file_group);
            $wanted_gid = $grpinfo['gid'];
            if ($wanted_gid !== $current_gid)
            {
                try
                {
                    !@chgrp($path, self::$file_group);
                    clearstatcache(true, $path);
                }
                // @codeCoverageIgnoreStart
                // Impossible to test - this would require a RO file system
                catch (Throwable $e)
                {
                    throw new IOException(
                        "Could not set group on " . $path . " to " . self::$file_group
                    );
                }
                // @codeCoverageIgnoreEnd
            }
        }
        
        if ($mode === null)
            $mode = $is_dir ? self::$dir_mode : self::$file_mode;

        if (!empty($mode))
        {
            $perms = self::getPermissions($path);
            $current_mode = $perms['mode'];
            
            if ($mode !== $current_mode)
            {
                try
                {
                    @chmod($path, $mode);
                    clearstatcache(true, $path);
                }
                // @codeCoverageIgnoreStart
                // Impossible to test - this would require a RO file system
                catch (Throwable $e)
                {
                    throw new IOException(
                        "Could not set mode on " . $path . " to " . $mode
                    );
                }
                // @codeCoverageIgnoreEnd
            }
        }
    }
1290290
function(callback) {
            // Optional permission modification
            if (disablePerms) {
              callback();
              return;
            }
            
            grunt.verbose.writeln('changing file perms...');

            // 511 = 0777 octal
            ftpout.raw.site('chmod', (file.mode & 511).toString(8), file.dest, function(err) {
              // Windows and some hosts don't implement the CHMOD site extension
              if (err && err.code !== 502 && err.code !== 504) {
                done(err);
                return;
              }

              grunt.verbose.writeln('done changing perms');
              callback();
            });
          }
54186
def write_file(path, content, owner='root', group='root', perms=0o444):
    """"""
    uid = pwd.getpwnam(owner).pw_uid
    gid = grp.getgrnam(group).gr_gid
    # lets see if we can grab the file and compare the context, to avoid doing
    # a write.
    existing_content = None
    existing_uid, existing_gid, existing_perms = None, None, None
    try:
        with open(path, 'rb') as target:
            existing_content = target.read()
        stat = os.stat(path)
        existing_uid, existing_gid, existing_perms = (
            stat.st_uid, stat.st_gid, stat.st_mode
        )
    except Exception:
        pass
    if content != existing_content:
        log("Writing file {} {}:{} {:o}".format(path, owner, group, perms),
            level=DEBUG)
        with open(path, 'wb') as target:
            os.fchown(target.fileno(), uid, gid)
            os.fchmod(target.fileno(), perms)
            if six.PY3 and isinstance(content, six.string_types):
                content = content.encode('UTF-8')
            target.write(content)
        return
    # the contents were the same, but we might still need to change the
    # ownership or permissions.
    if existing_uid != uid:
        log("Changing uid on already existing content: {} -> {}"
            .format(existing_uid, uid), level=DEBUG)
        os.chown(path, uid, -1)
    if existing_gid != gid:
        log("Changing gid on already existing content: {} -> {}"
            .format(existing_gid, gid), level=DEBUG)
        os.chown(path, -1, gid)
    if existing_perms != perms:
        log("Changing permissions on existing content: {} -> {}"
            .format(existing_perms, perms), level=DEBUG)
        os.chmod(path, perms)
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
64862
function resolvePath (path) {
  if (path) {
    // <rootDir>
    if (path.indexOf('<rootDir>') === 0) {
      return `"${path.replace('<rootDir>', root).replace(/\\/g, '\\\\')}"`
    } else {
      return `"${resolve(path).replace(/\\/g, '\\\\')}"`
    }
  } else {
    return ''
  }
}
1196771
def group_path(cls, project, group):
        """"""
        return google.api_core.path_template.expand(
            "projects/{project}/groups/{group}", project=project, group=group
        )
421191
protected function chgrpRecurse($path, $group) {

        if (!file_exists($path)) {
            return false;
        }

        if (!is_dir($path)) {
            return $this->chgrpReal($path, $group);
        }

        $result = $this->chgrpReal($path, $group);

        $allFiles = $this->getFileManager()->getFileList($path);
        foreach ($allFiles as $item) {
            $result &= $this->chgrpRecurse($path . Utils\Util::getSeparator() . $item, $group);
        }

        return (bool) $result;
    }
252468
def get_default_group(user):
    '''
    
    '''
    return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \
        if HAS_GRP and HAS_PWD \
        else None
687442
def _resolve_group_location(self, group: str) -> str:
        
        if os.path.isabs(group):
            possible_paths = [group]
        else:
            possible_paths = []
            for repository in self.setting_repositories:
                possible_paths.append(os.path.join(repository, group))

        for default_setting_extension in self.default_setting_extensions:
            number_of_paths = len(possible_paths)
            for i in range(number_of_paths):
                path_with_extension = "%s.%s" % (possible_paths[i], default_setting_extension)
                possible_paths.append(path_with_extension)

        for path in possible_paths:
            if os.path.exists(path):
                return path
        raise ValueError("Could not resolve location of settings identified by: \"%s\"" % group)
252277
def chown_r(path: str, user: str, group: str) -> None:
    
    for root, dirs, files in os.walk(path):
        for x in dirs:
            shutil.chown(os.path.join(root, x), user, group)
        for x in files:
            shutil.chown(os.path.join(root, x), user, group)
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
436844
def create_group(self, group_name, path='/'):
        
        params = {'GroupName' : group_name,
                  'Path' : path}
        return self.get_response('CreateGroup', params)
900617
def chown(path, user=None, group=None):
    """"""
    import os
    import pwd
    import grp
    uid = pwd.getpwnam(user).pw_uid if user else -1
    gid = grp.getgrnam(group).gr_gid if group else -1
    return os.chown(path, uid, gid)
478611
def _getgrnam(name, root=None):
    '''
    
    '''
    root = root or '/'
    passwd = os.path.join(root, 'etc/group')
    with salt.utils.files.fopen(passwd) as fp_:
        for line in fp_:
            line = salt.utils.stringutils.to_unicode(line)
            comps = line.strip().split(':')
            if len(comps) < 4:
                log.debug('Ignoring group line: %s', line)
                continue
            if comps[0] == name:
                # Generate a getpwnam compatible output
                comps[2] = int(comps[2])
                comps[3] = comps[3].split(',') if comps[3] else []
                return grp.struct_group(comps)
    raise KeyError('getgrnam(): name not found: {}'.format(name))