Search LDAP for records.
161434
def search(self, filter, attributes=None):
        """"""
        if attributes is None:
            attributes = ['*']

        if filter is None:
            filter = ["(objectclass=*)"]

        # Convert filter list into an LDAP-consumable format
        filterstr = "(&{})".format(''.join(filter))
        self.conn.search(
            search_base=self.basedn,
            search_filter=filterstr,
            search_scope=ldap3.SUBTREE,
            attributes=attributes)
        return self.conn.entries
706437
def get(method, hmc, uri, uri_parms, logon_required):
        """"""
        query_str = uri_parms[0]
        try:
            console = hmc.consoles.lookup_by_oid(None)
        except KeyError:
            raise InvalidResourceError(method, uri)
        result_ldap_srv_defs = []
        filter_args = parse_query_parms(method, uri, query_str)
        for ldap_srv_def in console.ldap_server_definitions.list(filter_args):
            result_ldap_srv_def = {}
            for prop in ldap_srv_def.properties:
                if prop in ('element-uri', 'name', 'type'):
                    result_ldap_srv_def[prop] = ldap_srv_def.properties[prop]
            result_ldap_srv_defs.append(result_ldap_srv_def)
        return {'ldap-server-definitions': result_ldap_srv_defs}
405625
def get_records_with_attachments(attachment_table, rel_object_field="REL_OBJECTID"):
    """"""
    if arcpyFound == False:
        raise Exception("ArcPy is required to use this function")
    OIDs = []
    with arcpy.da.SearchCursor(attachment_table,
                               [rel_object_field]) as rows:
        for row in rows:
            if not str(row[0]) in OIDs:
                OIDs.append("%s" % str(row[0]))
            del row
    del rows
    return OIDs
443425
protected Response<SearchResult> performLdapSearch(final String ldapURL) throws LdapException {
        val connectionFactory = prepareConnectionFactory(ldapURL);
        return this.searchExecutor.search(connectionFactory);
    }
708947
def _get_users(self, user_base):
        """""""
        results = self._search(
            getattr(self, '_%s_user_base' % user_base),
            '(objectClass=*)',
            ['*'],
            scope=ldap.SCOPE_ONELEVEL
        )
        for dn, attrs in results:
            uid = attrs.get('uid')[0].decode('utf-8', 'ignore')
            getattr(self, '_%s_users' % user_base)[uid] = FreeIPAUser(dn, attrs)
            # print(attrs)
        log.debug('%s users: %s' % (user_base.capitalize(), len(getattr(self, '_%s_users' % user_base))))
805398
def query(self, base, filterstr, attrlist=None):
		
		return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)
1272056
def search(self, query, fields=None, page=1, max_records=None, flatten=True):
        """"""
        if fields is None:
            fields = []
        page = int(page)
        pages = float('inf')
        data = {
            "query": query,
            "page": page,
            "fields": fields,
            "flatten": flatten
        }

        count = 0
        while page <= pages:
            payload = self._post(self.search_path, data=data)
            pages = payload['metadata']['pages']
            page += 1
            data["page"] = page

            for result in payload["results"]:
                yield result
                count += 1
                if max_records and count >= max_records:
                    return
160653
def get_log_entries_by_search(self, log_entry_query, log_entry_search):
        """"""
        # Implemented from azosid template for -
        # osid.resource.ResourceSearchSession.get_resources_by_search_template
        if not self._can('search'):
            raise PermissionDenied()
        return self._provider_session.get_log_entries_by_search(log_entry_query, log_entry_search)
1121564
private Response<SearchResult> searchForServiceById(final Long id) throws LdapException {
        val filter = LdapUtils.newLdaptiveSearchFilter(this.searchFilter,
            LdapUtils.LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME, CollectionUtils.wrap(id.toString()));
        return LdapUtils.executeSearchOperation(this.connectionFactory, this.baseDn, filter);
    }
682475
def _results(self, connection, msgid):
        
        try:
            kind, results = connection.result(msgid)
            if kind != ldap.RES_SEARCH_RESULT:
                results = []
        except ldap.LDAPError as e:
            results = []
            logger.error(u"result(%d) raised %s" % (msgid, pprint.pformat(e)))

        return self._process_results(results)
360157
def search(table: LdapObjectClass, query: Optional[Q] = None,
           database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:
    
    fields = table.get_fields()
    db_fields = {
        name: field
        for name, field in fields.items()
        if field.db_field
    }

    database = get_database(database)
    connection = database.connection

    search_options = table.get_search_options(database)

    iterator = tldap.query.search(
        connection=connection,
        query=query,
        fields=db_fields,
        base_dn=base_dn or search_options.base_dn,
        object_classes=search_options.object_class,
        pk=search_options.pk_field,
    )

    for dn, data in iterator:
        python_data = _db_to_python(data, table, dn)
        python_data = table.on_load(python_data, database)
        yield python_data
934905
def pagedsearch(self, ldap_filter, attributes):
		
		logger.debug('Paged search, filter: %s attributes: %s' % (ldap_filter, ','.join(attributes)))
		ctr = 0
		entries = self._con.extend.standard.paged_search(self._tree, ldap_filter, attributes = attributes, paged_size = self.ldap_query_page_size)
		for entry in entries:
			if 'raw_attributes' in entry and 'attributes' in entry:
				# TODO: return ldapuser object
				ctr += 1
				if ctr % self.ldap_query_page_size == 0:
					logger.info('New page requested. Result count: %d' % ctr)
				yield entry
770421
def get_user_groups(self, user):
        

        conn = self.bind
        try:
            if current_app.config['LDAP_OPENLDAP']:
                fields = \
                    [str(current_app.config['LDAP_GROUP_MEMBER_FILTER_FIELD'])]
                records = conn.search_s(
                    current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE,
                    ldap_filter.filter_format(
                        current_app.config['LDAP_GROUP_MEMBER_FILTER'],
                        (self.get_object_details(user, dn_only=True),)),
                    fields)
            else:
                records = conn.search_s(
                    current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE,
                    ldap_filter.filter_format(
                        current_app.config['LDAP_USER_OBJECT_FILTER'],
                        (user,)),
                    [current_app.config['LDAP_USER_GROUPS_FIELD']])

            conn.unbind_s()
            if records:
                if current_app.config['LDAP_OPENLDAP']:
                    group_member_filter = \
                        current_app.config['LDAP_GROUP_MEMBER_FILTER_FIELD']
                    if sys.version_info[0] > 2:
                        groups = [record[1][group_member_filter][0].decode(
                            'utf-8') for record in records]
                    else:
                        groups = [record[1][group_member_filter][0] for
                                  record in records]
                    return groups
                else:
                    if current_app.config['LDAP_USER_GROUPS_FIELD'] in \
                            records[0][1]:
                        groups = records[0][1][
                            current_app.config['LDAP_USER_GROUPS_FIELD']]
                        result = [re.findall(b'(?:cn=|CN=)(.*?),', group)[0]
                                  for group in groups]
                        if sys.version_info[0] > 2:
                            result = [r.decode('utf-8') for r in result]
                        return result
        except ldap.LDAPError as e:
            raise LDAPException(self.error(e.args))
1076562
def _do_search(conf):
    '''
    
    '''
    # Build LDAP connection args
    connargs = {}
    for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
        connargs[name] = _config(name, conf)
    if connargs['binddn'] and connargs['bindpw']:
        connargs['anonymous'] = False
    # Build search args
    try:
        _filter = conf['filter']
    except KeyError:
        raise SaltInvocationError('missing filter')
    _dn = _config('dn', conf)
    scope = _config('scope', conf)
    _lists = _config('lists', conf) or []
    _attrs = _config('attrs', conf) or []
    _dict_key_attr = _config('dict_key_attr', conf, 'dn')
    attrs = _lists + _attrs + [_dict_key_attr]
    if not attrs:
        attrs = None
    # Perform the search
    try:
        result = __salt__['ldap.search'](_filter, _dn, scope, attrs,
                                         **connargs)['results']
    except IndexError:  # we got no results for this search
        log.debug('LDAP search returned no results for filter %s', _filter)
        result = {}
    except Exception:
        log.critical(
            'Failed to retrieve pillar data from LDAP:\n', exc_info=True
        )
        return {}
    return result
857447
def list_records(self, domain, limit=None, offset=None):
        
        return domain.list_records(limit=limit, offset=offset)
1354160
function search_userdn($rcmail, $ds)
    {
        $search_user   = $rcmail->config->get('password_ldap_searchDN');
        $search_pass   = $rcmail->config->get('password_ldap_searchPW');
        $search_base   = $rcmail->config->get('password_ldap_search_base');
        $search_filter = $rcmail->config->get('password_ldap_search_filter');

        if (empty($search_filter)) {
            return false;
        }

        $this->_debug("C: Bind " . ($search_user ? $search_user : '[anonymous]'));

        // Bind
        if (!ldap_bind($ds, $search_user, $search_pass)) {
            $this->_debug("S: ".ldap_error($ds));
            return false;
        }

        $this->_debug("S: OK");

        $search_base   = rcube_ldap_password::substitute_vars($search_base);
        $search_filter = rcube_ldap_password::substitute_vars($search_filter);

        $this->_debug("C: Search $search_base for $search_filter");

        // Search for the DN
        if (!$sr = ldap_search($ds, $search_base, $search_filter)) {
            $this->_debug("S: ".ldap_error($ds));
            return false;
        }

        $found = ldap_count_entries($ds, $sr);

        $this->_debug("S: OK [found $found records]");

        // If no or more entries were found, return false
        if ($found != 1) {
            return false;
        }

        return ldap_get_dn($ds, ldap_first_entry($ds, $sr));
    }
427399
def _bind_for_search(anonymous=False, opts=None):
    '''
    
    '''
    # Get config params; create connection dictionary
    connargs = {}
    # config params (auth.ldap.*)
    params = {
        'mandatory': ['uri', 'server', 'port', 'starttls', 'tls',
                      'no_verify', 'anonymous',
                      'accountattributename', 'activedirectory'],
        'additional': ['binddn', 'bindpw', 'filter', 'groupclass',
                       'auth_by_group_membership_only'],
    }

    paramvalues = {}

    for param in params['mandatory']:
        paramvalues[param] = _config(param, opts=opts)

    for param in params['additional']:
        paramvalues[param] = _config(param, mandatory=False, opts=opts)

    paramvalues['anonymous'] = anonymous

    # Only add binddn/bindpw to the connargs when they're set, as they're not
    # mandatory for initializing the LDAP object, but if they're provided
    # initially, a bind attempt will be done during the initialization to
    # validate them
    if paramvalues['binddn']:
        connargs['binddn'] = paramvalues['binddn']
        if paramvalues['bindpw']:
            params['mandatory'].append('bindpw')

    for name in params['mandatory']:
        connargs[name] = paramvalues[name]

    if not paramvalues['anonymous']:
        if paramvalues['binddn'] and paramvalues['bindpw']:
            # search for the user's DN to be used for the actual authentication
            return _LDAPConnection(**connargs).ldap