使用DirectoryServices.Protocols进行LDAP搜索

599*_*599 5 directoryservices ldap active-directory

我们正在使用System.DirectoryServices.DirectorySearcher进行sAMAccountName查找。这很好用,只是当查询某个我们怀疑很大的AD时,搜索经常会超时。经过一些研究,我发现在针对大型AD查询时,使用System.DirectoryServices.Protocols进行搜索会更快。我正在尝试重新创建使用协议的内容,以查看超时是否会有所不同。这是当前存在的内容:

Dim Entry As New DirectoryEntry(anLDAPURL, aDomainUserName, aPassword)

Dim obj As Object = Entry.NativeObject 'Force Authentication on Active Directory Server

Dim Filter As String = String.Format("(sAMAccountName={0})", aDomainUserName)

Dim Search As New DirectorySearcher(Entry, Filter)
Search.PropertiesToLoad.Add(SID)
Search.PropertiesToLoad.Add(ACCOUNTISLOCKEDOUT)
Search.PropertiesToLoad.Add(ACCOUNTISDISABLED)

Dim Results As SearchResult = Search.FindOne()
Run Code Online (Sandbox Code Playgroud)

这可以正常工作并且非常快(除非在上述情况下超时)。这就是我想要将其更改为以便可以对其进行测试的内容:

Dim credentials As New System.Net.NetworkCredential(aDomainUserName, aPassword)
Dim directoryIdentifier As New System.DirectoryServices.Protocols.LdapDirectoryIdentifier("ldap-ad.example.org")

Using connection As New System.DirectoryServices.Protocols.LdapConnection(directoryIdentifier, credentials, Protocols.AuthType.Basic)
    Dim attributes() As String = {SID, ACCOUNTISLOCKEDOUT, ACCOUNTISDISABLED}

    Dim search As New System.DirectoryServices.Protocols.SearchRequest(
    "dc=example,dc=org",
    String.Format("(sAMAccountName={0})", aDomainUserName),
    Protocols.SearchScope.Subtree,
    attributes)

    Dim response As System.DirectoryServices.Protocols.SearchResponse = DirectCast(connection.SendRequest(search), System.DirectoryServices.Protocols.SearchResponse)
End Using
Run Code Online (Sandbox Code Playgroud)

上面的代码有效,因为它返回结果,但是比原始代码慢得多。我怀疑我尝试查询的方式效率低下,但是我不太确定如何设置它以便更快。

小智 5

我遇到了同样的问题,最终是由于方法返回结果中的“推荐追逐”造成的System.DirectoryServices.Protocols.LdapConnection.SendRequest。这是由于“假”域名“corp.org”没有任何 DNS 条目(因此SendRequest浪费了大量时间对结果进行 DNS 查找)。要禁用推荐追踪:

var conn = new LdapConnection(...);
conn.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
Run Code Online (Sandbox Code Playgroud)


Sea*_*all 0

根据SearchRequest构造函数 ( "dc=example,dc=org") 中的 LDAP 路径,您似乎在LdapDirectoryIdentifier构造函数 ( ldap-ad.example.org) 中指定了服务器。您是否尝试过仅指定域而不是服务器 ( example.org)?

当您搜索仅返回 0 或 1 个结果的索引属性时,我真的不明白这两种方法应该有何不同。