Searches (without recursion) LDAP groups
 @param [String] cn the group or user to search by
 @return [Array] LDAP groups for cn, one level deep, unsorted
349246
def ldap_member_of(cn)
      return [] if service.nil?
      entry = service.search(base: tree,
                                filter: Net::LDAP::Filter.equals('cn', cn),
                                attributes: ['memberof']).first
      if entry.nil?
        []
      else
        entry['memberof'].collect { |mo| mo.split(',').first.split('=')[1] }
      end
    end
1111861
def groups
      children.find_all {|child| child.is_a?(Group) }.map do |group|
        group.supergroup = self
        group
      end
    end
505322
def get_group_members(self, group):
        

        conn = self.bind
        try:
            records = conn.search_s(
                current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE,
                ldap_filter.filter_format(
                    current_app.config['LDAP_GROUP_OBJECT_FILTER'], (group,)),
                [current_app.config['LDAP_GROUP_MEMBERS_FIELD']])
            conn.unbind_s()
            if records:
                if current_app.config['LDAP_GROUP_MEMBERS_FIELD'] in \
                        records[0][1]:
                    members = records[0][1][
                        current_app.config['LDAP_GROUP_MEMBERS_FIELD']]
                    if sys.version_info[0] > 2:
                        members = [m.decode('utf-8') for m in members]
                    return members
        except ldap.LDAPError as e:
            raise LDAPException(self.error(e.args))
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)]
1192806
def GetAll(root_group_id,alias=None,session=None):
		
		if not alias:  alias = clc.v2.Account.GetAlias(session=session)

		groups = []
		for r in clc.v2.API.Call('GET','groups/%s/%s' % (alias,root_group_id),{}, session=session)['groups']:
			groups.append(Group(id=r['id'],alias=alias,group_obj=r,session=session))

		return(groups)
1155903
private List<LDAPGroup> getGroups(final DirContext ldap, final String dn) throws NamingException
	{
		// Get the DN of all grouos the user is directly/indirectly a member of
		final NamingEnumeration<SearchResult> answer;
		{
			SearchControls search = new SearchControls();

			search.setSearchScope(SearchControls.SUBTREE_SCOPE);
			search.setReturningAttributes(new String[]{"dn"});

			final String searchFilter = String.format(this.ldapGroupFilter, dn);

			answer = ldap.search(ldapSearchBase, searchFilter, search);
		}

		List<LDAPGroup> groups = new ArrayList<>();

		while (answer.hasMoreElements())
		{
			SearchResult sr = answer.next();

			final String groupDN = sr.getNameInNamespace();

			groups.add(dnToLdapGroup(groupDN));
		}

		return groups;
	}
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
1212376
function all_groups($include_desc = false,
                        $search = "*",
                        $sorted = true,
                        $local_group = FALSE // $local_group switch added by SysCo/al
                       )
    {
        $this->_warning_message = "";
        if (!$this->_bind){ return (false); }

        if (2 == $this->_ldap_server_type) { // Generic LDAP
            $filter="(|(objectClass=posixGroup)(objectClass=groupofNames))";
            $fields=array($this->_group_cn_identifier,"description");
        } else { // Active Directory
            //perform the search and grab all their details
            if ($local_group) {
                $group_account_type = "(|(samaccounttype=".ADLDAP_SECURITY_LOCAL_GROUP.")(samaccounttype=". ADLDAP_SECURITY_GLOBAL_GROUP."))";
            } else {
                $group_account_type = "(samaccounttype=".ADLDAP_SECURITY_GLOBAL_GROUP.")";
            }
            $filter = "(&(objectCategory=group)".$group_account_type."(cn=".$search."))";
            $fields = array($this->_group_cn_identifier,"description");
        }

        $groups_array = array();

        $pageSize = 1000;
        $page_cookie = '';
        do {
            if (function_exists('ldap_control_paged_result')) {
                ldap_control_paged_result($this->_conn, $pageSize, false, $page_cookie);
            }
            $sr = @ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        
            if ((!function_exists('ldap_control_paged_result')) && (4 == ldap_errno($this->_conn))) {
                $cr = @ldap_count_entries($this->_conn,$sr);
                $this->_warning_message = "LDAP server cannot return more than $cr records.";
            }
        
            $entries = $this->ldap_get_entries_raw($sr);

            for ($i=0; $i<$entries["count"]; $i++){
                if ($include_desc && strlen($entries[$i]["description"][0]) > 0 ){
                    $groups_array[ $entries[$i][$this->_group_cn_identifier][0] ] = $entries[$i]["description"][0];
                } elseif ($include_desc){
                    $groups_array[ $entries[$i][$this->_group_cn_identifier][0] ] = $entries[$i][$this->_group_cn_identifier][0];
                } else {
                    array_push($groups_array, $entries[$i][$this->_group_cn_identifier][0]);
                }
            }
            if (function_exists('ldap_control_paged_result_response')) {
                ldap_control_paged_result_response($this->_conn, $sr, $page_cookie);
            }
        }
        while($page_cookie !== null && $page_cookie != '');
        
        if (function_exists('ldap_control_paged_result')) {
            // Reset LDAP paged result
            ldap_control_paged_result($this->_conn, $pageSize, false);
        }
        
        if( $sorted ){
            asort($groups_array);
        }
        
        return ($groups_array);
        
    }
1307797
function all_users($include_desc = false, $search = "*", $sorted = true){
        if (!$this->_bind){
            return (false);
        }
        
        //perform the search and grab all their details
        $filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=".$search."))";
        $fields=array($this->_cn_identifier,"displayname");
        $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
        $entries = $this->ldap_get_entries_raw($sr);

        $users_array = array();
        for ($i=0; $i<$entries["count"]; $i++){
            if ($include_desc && strlen($entries[$i]["displayname"][0])>0){
                $users_array[ $entries[$i][$this->_cn_identifier][0] ] = $entries[$i]["displayname"][0];
            } elseif ($include_desc){
                $users_array[ $entries[$i][$this->_cn_identifier][0] ] = $entries[$i][$this->_cn_identifier][0];
            } else {
                array_push($users_array, $entries[$i][$this->_cn_identifier][0]);
            }
        }
        if ($sorted){ asort($users_array); }
        return ($users_array);
    }
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()
140503
def find(source = @source)
      scope = 0
      filter = "(objectClass=*)"
      if source.respond_to?(:search2_ext)
        source.search2(
          to_s,
          scope,
          filter
        )
      elsif source.respond_to?(:search)
        Array(source.search(
          :base => to_s,
          :scope => scope,
          :filter => filter,
          :limit => 1
        ))
      else
        raise RuntimeError, "missing or invalid source for LDAP search", caller
      end.first
    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)
696556
def search( self, base=False, trim=False, objects=False, **kwargs ):
        
        scope = pyldap.SCOPE_SUBTREE
        if not base:
            base = self.users

        filterstr =''
        for key, value in kwargs.iteritems():
            filterstr += '({0}={1})'.format(key,value)
            if key == 'dn':
                filterstr = '(objectClass=*)'
                base = value
                scope = pyldap.SCOPE_BASE
                break

        if len(kwargs) > 1:
            filterstr = '(&'+filterstr+')'

        result = self.ldap.search_s(base, pyldap.SCOPE_SUBTREE, filterstr, ['*','+'])
        if base == self.users:
            for member in result:
                groups = self.getGroups(member[0])
                member[1]['groups'] = groups
                if 'eboard' in member[1]['groups']:
                    member[1]['committee'] = self.search(base=self.committees, \
                           head=member[0])[0][1]['cn'][0]
        if objects:
            return self.memberObjects(result)
        finalResult = self.trimResult(result) if trim else result
        return finalResult
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
1163669
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE):
        """"""
        try:
            results = self._conn.search_s(base, scope, fltr, attrs)
        except Exception as e:
            log.exception(self._get_ldap_msg(e))
            results = False
        return results
265524
def get_groups(self, load):
        '''
        
        '''
        if 'eauth' not in load:
            return False
        fstr = '{0}.groups'.format(load['eauth'])
        if fstr not in self.auth:
            return False
        fcall = salt.utils.args.format_call(
            self.auth[fstr],
            load,
            expected_extra_kws=AUTH_INTERNAL_KEYWORDS)
        try:
            return self.auth[fstr](*fcall['args'], **fcall['kwargs'])
        except IndexError:
            return False
        except Exception:
            return None
107273
def get_users_by_roles(roles=None):
    
    if not isinstance(roles, (tuple, list)):
        roles = [roles]
    mtool = get_tool("portal_membership")
    return mtool.searchForMembers(roles=roles)