Search for groups

    CLI Example:

    .. code-block:: bash

        salt '*' keystoneng.group_search name=group1
        salt '*' keystoneng.group_search domain_id=b62e76fbeeff4e8fb77073f591cf211e
550600
def group_search(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.search_groups(**kwargs)
16921
def Search(self,key):
		

		results = []
		for group in self.groups:
			if group.id.lower().find(key.lower()) != -1:  results.append(group)
			elif group.name.lower().find(key.lower()) != -1:  results.append(group)
			elif group.description.lower().find(key.lower()) != -1:  results.append(group)

		return(results)
1184398
def list_groups(region=None, key=None, keyid=None, profile=None):
    '''
    

    '''
    return [a.name for a in get_all_groups(region=region, key=key, keyid=keyid, profile=profile)]
13548
def user_groups(self, ldap_user, group_search):
        
        groups = []

        try:
            user_uid = ldap_user.attrs["uid"][0]

            if "gidNumber" in ldap_user.attrs:
                user_gid = ldap_user.attrs["gidNumber"][0]
                filterstr = "(|(gidNumber={})(memberUid={}))".format(
                    self.ldap.filter.escape_filter_chars(user_gid),
                    self.ldap.filter.escape_filter_chars(user_uid),
                )
            else:
                filterstr = "(memberUid={})".format(
                    self.ldap.filter.escape_filter_chars(user_uid)
                )

            search = group_search.search_with_additional_term_string(filterstr)
            groups = search.execute(ldap_user.connection)
        except (KeyError, IndexError):
            pass

        return groups
1351943
def search_groups(self, keyword, start=0):
        
        xml = self.api.xml(API_GROUP_SEARCH_GROUPS % (start, keyword))
        xml_results = xml.xpath('//div[@class="groups"]/div[@class="result"]')
        results = []
        for item in xml_results:
            try:
                url = item.xpath('.//h3/a/@href')[0]
                info = item.xpath('.//div[@class="content"]/div[@class="info"]/text()')[0].strip(' ')
                onclick = item.xpath('.//h3/a/@onclick')[0]
                meta = {
                    'icon': item.xpath('.//img/@src')[0],
                    'id': re.search(r'sid[^\d]+(\d+)', onclick).groups()[0],
                    'url': url,
                    'alias': url.rstrip('/').rsplit('/', 1)[1],
                    'name': item.xpath('.//h3/a/text()')[0],
                    'user_count': int(re.match(r'\d+', info).group()),
                    'user_alias': re.search(r'个(.+)\s*在此', info).groups()[0],
                }
                results.append(meta)
            except Exception as e:
                self.api.logger.exception('parse search groups result error: %s' % e)
        return build_list_result(results, xml)
1367556
async def query(
            cls, *,
            hostnames: typing.Iterable[str] = None,
            domains: typing.Iterable[str] = None,
            zones: typing.Iterable[str] = None,
            macs: typing.Iterable[str] = None,
            system_ids: typing.Iterable[str] = None,
            agent_name: str = None,
            level: typing.Union[Level, int, str] = None,
            before: int = None,
            after: int = None,
            limit: int = None,
            owner: typing.Union[User, str] = None):
        """"""

        if before is not None and after is not None:
            raise ValueError("Specify either `before` or `after`, not both.")

        params = {}

        if hostnames is not None:
            params["hostname"] = list(hostnames)
        if domains is not None:
            params["domain"] = list(domains)
        if zones is not None:
            params["zone"] = list(zones)
        if macs is not None:
            params["mac_address"] = list(macs)
        if system_ids is not None:
            params["id"] = list(system_ids)
        if agent_name is not None:
            params["agent_name"] = [agent_name]
        if level is not None:
            level = Level.normalise(level)
            params["level"] = [level.name]
        if before is not None:
            params["before"] = ["{:d}".format(before)]
        if after is not None:
            params["after"] = ["{:d}".format(after)]
        if limit is not None:
            params["limit"] = ["{:d}".format(limit)]
        if owner is not None:
            if isinstance(owner, User):
                params["owner"] = [owner.username]
            elif isinstance(owner, str):
                params["owner"] = [owner]
            else:
                raise TypeError(
                    "owner must be either User or str, not %s" % (
                        type(owner).__name__))

        data = await cls._handler.query(**params)
        return cls(data)
1158255
public static String getGroupName(long gid) throws IOException {
    if (OSUtils.isLinux()) {
      String script = "getent group " + gid + " | cut -d: -f1";
      return ShellUtils.execCommand("bash", "-c", script).trim();
    } else if (OSUtils.isMacOS()) {
      String script = "dscl . list /Groups PrimaryGroupID | awk '($2 == \""
          + gid + "\") { print $1 }'";
      return ShellUtils.execCommand("bash", "-c", script).trim();
    }
    return "";
  }
1297255
def get_group(self, group_id):
        
        def process_result(result):
            return Group(self, result)

        return Command('get', [ROOT_GROUPS, group_id],
                       process_result=process_result)
684084
protected WsGroup findGroupFromKey(String key) {
        WsGroup wsGroup = null;

        if (key != null) {

            GcFindGroups gcFindGroups = new GcFindGroups();
            gcFindGroups.addGroupName(key);
            WsFindGroupsResults results = gcFindGroups.execute();

            // if no results were returned, return null
            if (results != null
                    && results.getGroupResults() != null
                    && results.getGroupResults().length > 0) {

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "found group from key " + key + ": " + results.getGroupResults()[0]);
                }

                wsGroup = results.getGroupResults()[0];
            }
        }

        return wsGroup;
    }
912465
def get_secgroup_id(kwargs=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The get_secgroup_id function must be called with -f or --function.'
        )

    if kwargs is None:
        kwargs = {}

    name = kwargs.get('name', None)
    if name is None:
        raise SaltCloudSystemExit(
            'The get_secgroup_id function requires a \'name\'.'
        )

    try:
        ret = list_security_groups()[name]['id']
    except KeyError:
        raise SaltCloudSystemExit(
            'The security group \'{0}\' could not be found.'.format(name)
        )

    return ret
825069
def filter_group_names(groups, patterns):
    
    group_names = [g['logGroupName'] for g in groups]
    matched = set()
    for p in patterns:
        matched.update(fnmatch.filter(group_names, p))
    return [g for g in groups if g['logGroupName'] in matched]
49083
function(i, group_keys, callback) {
                if (i >= group_keys.length) {
                    return callback(replacement);
                }

                var processNextGroup = function() {
                        processGroup(++i, group_keys, callback);
                    },
                    block = match[group_keys[i]];

                // if there is no match here then move on
                if (!block) {
                    return processNextGroup();
                }

                var group = pattern['matches'][group_keys[i]],
                    language = group['language'],

                    /**
                     * process group is what group we should use to actually process
                     * this match group
                     *
                     * for example if the subgroup pattern looks like this
                     * 2: {
                     *     'name': 'keyword',
                     *     'pattern': /true/g
                     * }
                     *
                     * then we use that as is, but if it looks like this
                     *
                     * 2: {
                     *     'name': 'keyword',
                     *     'matches': {
                     *          'name': 'special',
                     *          'pattern': /whatever/g
                     *      }
                     * }
                     *
                     * we treat the 'matches' part as the pattern and keep
                     * the name around to wrap it with later
                     */
                    process_group = group['name'] && group['matches'] ? group['matches'] : group,

                    /**
                     * takes the code block matched at this group, replaces it
                     * with the highlighted block, and optionally wraps it with
                     * a span with a name
                     *
                     * @param {string} block
                     * @param {string} replace_block
                     * @param {string|null} match_name
                     */
                    _replaceAndContinue = function(block, replace_block, match_name) {
                        replacement = _replaceAtPosition(_indexOfGroup(match, group_keys[i]), block, match_name ? _wrapCodeInSpan(match_name, replace_block) : replace_block, replacement);
                        processNextGroup();
                    };

                // if this is a sublanguage go and process the block using that language
                if (language) {
                    return _highlightBlockForLanguage(block, language, function(code) {
                        _replaceAndContinue(block, code);
                    });
                }

                // if this is a string then this match is directly mapped to selector
                // so all we have to do is wrap it in a span and continue
                if (typeof group === 'string') {
                    return _replaceAndContinue(block, block, group);
                }

                // the process group can be a single pattern or an array of patterns
                // _processCodeWithPatterns always expects an array so we convert it here
                _processCodeWithPatterns(block, process_group.length ? process_group : [process_group], function(code) {
                    _replaceAndContinue(block, code, group['matches'] ? group['name'] : 0);
                });
            }
916537
@Override
    public Node getGroup(final String cn) {
        try {
            String query = "(&(objectClass=" + groupObjectClass + ")(" + groupIdentifyer + "=" + cn + "))";
            SearchResult searchResult;
            Attributes attributes;
            SearchControls controls = new SearchControls();
            controls.setReturningAttributes(new String[]{LdapKeys.ASTERISK, LdapKeys.MODIFY_TIMESTAMP, LdapKeys.MODIFIERS_NAME, LdapKeys.ENTRY_UUID});
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> results = ctx.search("", query, controls);
            queryCount++;
            if (results.hasMore()) {
                LdapGroup group = new LdapGroup(cn, this);
            	searchResult = results.next();
                group.setDn(searchResult.getNameInNamespace());
                attributes = searchResult.getAttributes();
                group = fillAttributesInGroup((LdapGroup) group, attributes);
                return group;
            }
        } catch (NamingException ex) {
            handleNamingException(instanceName + ":" + cn, ex);
        }
       return new LdapGroup();
    }
433743
def security_groups sgs
      for sg in sgs
        @logger.debug "Openstack: Looking up security group '#{sg}'"
        @compute_client.security_groups.find { |x| x.name == sg } || raise("Couldn't find security group: #{sg}")
        sgs
      end
    end
839885
def search(self, filter, base_dn=None, attrs=None, scope=None,
               timeout=None, limit=None):
        
        if base_dn is None:
            base_dn = self._search_defaults.get('base_dn', '')
        if attrs is None:
            attrs = self._search_defaults.get('attrs', None)
        if scope is None:
            scope = self._search_defaults.get('scope', ldap.SCOPE_SUBTREE)
        if timeout is None:
            timeout = self._search_defaults.get('timeout', -1)
        if limit is None:
            limit = self._search_defaults.get('limit', 0)

        results = self.connection.search_ext_s(
            base_dn, scope, filter, attrs, timeout=timeout, sizelimit=limit)
        return self.to_items(results)
91101
def user_groups(self, ldap_user, group_search):
        
        group_info_map = {}  # Maps group_dn to group_info of groups we've found
        member_dn_set = {ldap_user.dn}  # Member DNs to search with next
        handled_dn_set = set()  # Member DNs that we've already searched with

        while len(member_dn_set) > 0:
            group_infos = self.find_groups_with_any_member(
                member_dn_set, group_search, ldap_user.connection
            )
            new_group_info_map = {info[0]: info for info in group_infos}
            group_info_map.update(new_group_info_map)
            handled_dn_set.update(member_dn_set)

            # Get ready for the next iteration. To avoid cycles, we make sure
            # never to search with the same member DN twice.
            member_dn_set = set(new_group_info_map.keys()) - handled_dn_set

        return group_info_map.values()
1083889
def NameGroups(data_arr,id_key):
		
		new_data_arr = []
		for data in data_arr:
			try:
				data_arr[id_key] = clc._GROUP_MAPPING[data[id_key]]
			except:
				pass
			new_data_arr.append(data)
		if clc.args:  clc.v1.output.Status("ERROR",2,"Group name conversion not yet implemented")
		return(new_data_arr)