Return information about a group

    name
        Name of the group

    root
        Directory to chroot into

    CLI Example:

    .. code-block:: bash

        salt '*' group.info foo
771307
def info(name, root=None):
    '''
    
    '''
    if root is not None:
        getgrnam = functools.partial(_getgrnam, root=root)
    else:
        getgrnam = functools.partial(grp.getgrnam)

    try:
        grinfo = getgrnam(name)
    except KeyError:
        return {}
    else:
        return _format_info(grinfo)
550888
def chgid(name, gid):
    '''
    
    '''
    if not isinstance(gid, int):
        raise SaltInvocationError('gid must be an integer')
    pre_gid = __salt__['file.group_to_gid'](name)
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError(
            'Group \'{0}\' does not exist'.format(name)
        )
    if gid == pre_info['gid']:
        return True
    cmd = ['dseditgroup', '-o', 'edit', '-i', gid, name]
    return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
849840
def get_group_key_line(self, data, key):
        
        idx = -1
        for i, line in enumerate(data.splitlines()):
            if isin_start(self.groups[key], line):
                idx = i
        return idx
1296697
def info(name):
    '''
    
    '''
    if HAS_SPWD:
        try:
            data = spwd.getspnam(name)
            ret = {
                'name': data.sp_nam,
                'passwd': data.sp_pwd,
                'lstchg': data.sp_lstchg,
                'min': data.sp_min,
                'max': data.sp_max,
                'warn': data.sp_warn,
                'inact': data.sp_inact,
                'expire': data.sp_expire}
        except KeyError:
            ret = {
                'name': '',
                'passwd': '',
                'lstchg': '',
                'min': '',
                'max': '',
                'warn': '',
                'inact': '',
                'expire': ''}
        return ret

    # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost
    # Return what we can know
    ret = {
        'name': '',
        'passwd': '',
        'lstchg': '',
        'min': '',
        'max': '',
        'warn': '',
        'inact': '',
        'expire': ''}

    try:
        data = pwd.getpwnam(name)
        ret.update({
            'name': name
        })
    except KeyError:
        return ret

    # To compensate for lack of spwd module, read in password hash from /etc/shadow
    s_file = '/etc/shadow'
    if not os.path.isfile(s_file):
        return ret
    with salt.utils.files.fopen(s_file, 'rb') as ifile:
        for line in ifile:
            comps = line.strip().split(':')
            if comps[0] == name:
                ret.update({'passwd': comps[1]})

    # For SmartOS `passwd -s <username>` and the output format is:
    #   name status mm/dd/yy min max warn
    #
    # Fields:
    #  1. Name: username
    #  2. Status:
    #      - LK: locked
    #      - NL: no login
    #      - NP: No password
    #      - PS: Password
    #  3. Last password change
    #  4. Minimum age
    #  5. Maximum age
    #  6. Warning period

    output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False)
    if output['retcode'] != 0:
        return ret

    fields = output['stdout'].split()
    if len(fields) == 2:
        # For example:
        #   root      NL
        return ret
    # We have all fields:
    #   buildbot L 05/09/2013 0 99999 7
    ret.update({
        'name': data.pw_name,
        'lstchg': fields[2],
        'min': int(fields[3]),
        'max': int(fields[4]),
        'warn': int(fields[5]),
        'inact': '',
        'expire': ''
    })
    return ret
77231
def list_env(saltenv='base'):
    '''
    
    '''
    ret = {}
    if saltenv not in __opts__['pillar_roots']:
        return ret
    for f_root in __opts__['pillar_roots'][saltenv]:
        ret[f_root] = {}
        for root, dirs, files in salt.utils.path.os_walk(f_root):
            sub = ret[f_root]
            if root != f_root:
                # grab subroot ref
                sroot = root
                above = []
                # Populate the above dict
                while not os.path.samefile(sroot, f_root):
                    base = os.path.basename(sroot)
                    if base:
                        above.insert(0, base)
                    sroot = os.path.dirname(sroot)
                for aroot in above:
                    sub = sub[aroot]
            for dir_ in dirs:
                sub[dir_] = {}
            for fn_ in files:
                sub[fn_] = 'f'
    return ret
327183
def RootGroup(self):
		

		return(clc.v2.Group(id=self.root_group_id,alias=self.alias,session=self.session))
961085
def group_list():
    '''
    
    '''
    ret = {'installed': [],
           'available': [],
           'installed environments': [],
           'available environments': [],
           'available languages': {}}

    section_map = {
        'installed groups:': 'installed',
        'available groups:': 'available',
        'installed environment groups:': 'installed environments',
        'available environment groups:': 'available environments',
        'available language groups:': 'available languages',
    }

    out = __salt__['cmd.run_stdout'](
        [_yum(), 'grouplist', 'hidden'],
        output_loglevel='trace',
        python_shell=False
    )
    key = None
    for line in salt.utils.itertools.split(out, '\n'):
        line_lc = line.lower()
        if line_lc == 'done':
            break

        section_lookup = section_map.get(line_lc)
        if section_lookup is not None and section_lookup != key:
            key = section_lookup
            continue

        # Ignore any administrative comments (plugin info, repo info, etc.)
        if key is None:
            continue

        line = line.strip()
        if key != 'available languages':
            ret[key].append(line)
        else:
            match = re.match(r'(.+) \[(.+)\]', line)
            if match:
                name, lang = match.groups()
                ret[key][line] = {'name': name, 'language': lang}
    return ret
1097199
def get_group_names(self):
        
        if self._group_names is None:
            self._load_cached_attr("_group_names")

        if self._group_names is None:
            group_infos = self._get_group_infos()
            self._group_names = {
                self._group_type.group_name_from_info(group_info)
                for group_info in group_infos
            }
            self._cache_attr("_group_names")

        return self._group_names
303952
def info(name, path=None):
    '''
    
    '''
    cachekey = 'lxc.info.{0}{1}'.format(name, path)
    try:
        return __context__[cachekey]
    except KeyError:
        _ensure_exists(name, path=path)
        cpath = get_root_path(path)
        try:
            conf_file = os.path.join(cpath, name, 'config')
        except AttributeError:
            conf_file = os.path.join(cpath, six.text_type(name), 'config')

        if not os.path.isfile(conf_file):
            raise CommandExecutionError(
                'LXC config file {0} does not exist'.format(conf_file)
            )

        ret = {}
        config = []
        with salt.utils.files.fopen(conf_file) as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                comps = [x.strip() for x in
                         line.split('#', 1)[0].strip().split('=', 1)]
                if len(comps) == 2:
                    config.append(tuple(comps))

        ifaces = []
        current = None

        for key, val in config:
            if key == 'lxc.network.type':
                current = {'type': val}
                ifaces.append(current)
            elif not current:
                continue
            elif key.startswith('lxc.network.'):
                current[key.replace('lxc.network.', '', 1)] = val
        if ifaces:
            ret['nics'] = ifaces

        ret['rootfs'] = next(
            (x[1] for x in config if x[0] == 'lxc.rootfs'),
            None
        )
        ret['state'] = state(name, path=path)
        ret['ips'] = []
        ret['public_ips'] = []
        ret['private_ips'] = []
        ret['public_ipv4_ips'] = []
        ret['public_ipv6_ips'] = []
        ret['private_ipv4_ips'] = []
        ret['private_ipv6_ips'] = []
        ret['ipv4_ips'] = []
        ret['ipv6_ips'] = []
        ret['size'] = None
        ret['config'] = conf_file

        if ret['state'] == 'running':
            try:
                limit = int(get_parameter(name, 'memory.limit_in_bytes'))
            except (CommandExecutionError, TypeError, ValueError):
                limit = 0
            try:
                usage = int(get_parameter(name, 'memory.usage_in_bytes'))
            except (CommandExecutionError, TypeError, ValueError):
                usage = 0
            free = limit - usage
            ret['memory_limit'] = limit
            ret['memory_free'] = free
            size = run_stdout(name, 'df /', path=path, python_shell=False)
            # The size is the 2nd column of the last line
            ret['size'] = size.splitlines()[-1].split()[1]

            # First try iproute2
            ip_cmd = run_all(
                name, 'ip link show', path=path, python_shell=False)
            if ip_cmd['retcode'] == 0:
                ip_data = ip_cmd['stdout']
                ip_cmd = run_all(
                    name, 'ip addr show', path=path, python_shell=False)
                ip_data += '\n' + ip_cmd['stdout']
                ip_data = salt.utils.network._interfaces_ip(ip_data)
            else:
                # That didn't work, try ifconfig
                ip_cmd = run_all(
                    name, 'ifconfig', path=path, python_shell=False)
                if ip_cmd['retcode'] == 0:
                    ip_data = \
                        salt.utils.network._interfaces_ifconfig(
                            ip_cmd['stdout'])
                else:
                    # Neither was successful, give up
                    log.warning(
                        'Unable to run ip or ifconfig in container \'%s\'', name
                    )
                    ip_data = {}

            ret['ipv4_ips'] = salt.utils.network.ip_addrs(
                include_loopback=True,
                interface_data=ip_data
            )
            ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
                include_loopback=True,
                interface_data=ip_data
            )
            ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
            for address in ret['ipv4_ips']:
                if address == '127.0.0.1':
                    ret['private_ips'].append(address)
                    ret['private_ipv4_ips'].append(address)
                elif salt.utils.cloud.is_public_ip(address):
                    ret['public_ips'].append(address)
                    ret['public_ipv4_ips'].append(address)
                else:
                    ret['private_ips'].append(address)
                    ret['private_ipv4_ips'].append(address)
            for address in ret['ipv6_ips']:
                if address == '::1' or address.startswith('fe80'):
                    ret['private_ips'].append(address)
                    ret['private_ipv6_ips'].append(address)
                else:
                    ret['public_ips'].append(address)
                    ret['public_ipv6_ips'].append(address)

        for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
            ret[key].sort(key=_ip_sort)
        __context__[cachekey] = ret
    return __context__[cachekey]
443
def group_id(self):
        
        if self.derived_from is not None:
            return self.derived_from.group_id()
        if self.file_uuid is None:
            return None
        return utils.GROUP_ID_PREFIX + self.file_uuid
162350
def chshell(name, shell):
    '''
    
    '''
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError(
            'User \'{0}\' does not exist'.format(name)
        )
    if shell == pre_info['shell']:
        return True
    cmd = ['usermod', '-s', shell, name]
    __salt__['cmd.run'](cmd, python_shell=False)
    return info(name).get('shell') == shell
831305
def get(name):
    '''
    
    '''
    cmd = 'sysctl -n {0}'.format(name)
    out = __salt__['cmd.run'](cmd, python_shell=False)
    return out
241306
def deluser(name, username):
    '''
    
    '''
    grp_info = __salt__['group.info'](name)

    if username not in grp_info['members']:
        return True

    # Note: pw exits with code 65 if group is unknown
    retcode = __salt__['cmd.retcode']('pw groupmod {0} -d {1}'.format(
        name, username), python_shell=False)

    return not retcode
1227348
def dir_attribs(location, mode=None, owner=None,
                group=None, recursive=False, use_sudo=False):
    
    args = ''
    if recursive:
        args = args + ' -R '

    if mode:
        if use_sudo:
            sudo('chmod %s %s %s' % (args, mode,  location))
        else:
            run('chmod %s %s %s' % (args, mode,  location))
    if owner:
        if use_sudo:
            sudo('chown %s %s %s' % (args, owner, location))
        else:
            run('chown %s %s %s' % (args, owner, location))
    if group:
        if use_sudo:
            sudo('chgrp %s %s %s' % (args, group, location))
        else:
            run('chgrp %s %s %s' % (args, group, location))
    return True
57362
def get_group_by_name(self, group_name: str) -> typing.Optional['Group']:
        
        VALID_STR.validate(group_name, 'get_group_by_name')
        for group in self.groups:

            if group.group_name == group_name:
                return group
        return None
312961
def deluser(name, username, root=None):
    '''
    
    '''
    grp_info = __salt__['group.info'](name)
    try:
        if username in grp_info['members']:
            cmd = 'chgrpmem -m - {0} {1}'.format(username, name)
            ret = __salt__['cmd.run'](cmd, python_shell=False)
            return not ret['retcode']
        else:
            return True
    except Exception:
        return True
75384
def _resolve_user_group_names(opts):
    '''
    
    '''
    name_id_opts = {'uid': 'user.info',
                    'gid': 'group.info'}
    for ind, opt in enumerate(opts):
        if opt.split('=')[0] in name_id_opts:
            _givenid = opt.split('=')[1]
            _param = opt.split('=')[0]
            _id = _givenid
            if not re.match('[0-9]+$', _givenid):
                _info = __salt__[name_id_opts[_param]](_givenid)
                if _info and _param in _info:
                    _id = _info[_param]
            opts[ind] = _param + '=' + six.text_type(_id)
        opts[ind] = opts[ind].replace('\\040', '\\ ')
    return opts