【问题标题】:LDAP: Enumerate Organizational Unit usersLDAP:枚举组织单位用户
【发布时间】:2010-07-28 17:27:14
【问题描述】:

我正在尝试使用 LDAP (DirectorySearcher class) 列出位于域内某个组织单位中的所有用户。

我要连接的域不是当前域,并且我要查看的 OU 位于非常深的路径中,其中一些 OU 名称在其他地方重复,例如:

MyDomain.LOCAL/MyCompany/Clients/Contoso/Financial Site/Financial Services/Users

我可以使用以下代码列出域内的所有用户:

// Build the directory entry
var directoryEntry = new DirectoryEntry(_ldapServer, _domain + "\\" +
    _systemUser, _systemPassword);
try
{
    // Bind to the native AdsObject to force authentication of the system user.
    // It will throw an exception if this is an invalid account
    object obj = directoryEntry.NativeObject;
}
catch (Exception ex)
{
    throw new Exception("Error authenticating system user. " + ex.Message, ex);
}

// create a directory searcher for that OU  
DirectorySearcher users = new DirectorySearcher(directoryEntry);

// set the filter to get just the users
users.Filter = "(&(objectClass=user)(objectCategory=Person))";

// add the attributes you want to grab from the search
users.PropertiesToLoad.Add("givenName");
users.PropertiesToLoad.Add("sn");
users.PropertiesToLoad.Add("mail"); 
users.PropertiesToLoad.Add("name"); 

// grab the users and do whatever you need to do with them
var allFound = users.FindAll();
foreach (SearchResult oResult in allFound)
{
    // etc
}

这很有效,并获取了位于根(域)中的所有用户的巨大列表。
但是,我希望获取特定 OU 下的用户。

我尝试了以下行:

var directoryEntry = new DirectoryEntry(_ldapServer +
    "/ou=MyCompany/Clients/Contoso/Financial Site/Financial Services/Users",
    _domain + "\\" + _systemUser, _systemPassword);

我得到了错误:

验证系统用户时出错。发生操作错误。

有谁知道我如何在DirectorySearcher 中更具体地说明我感兴趣的 OU?


已解决!

最终的路径字符串(以我为例)应如下所示(不含换行符):

LDAP://DomainControllerServer/OU=Users,OU=金融服务,
    OU=Financial Site,OU=Contoso,OU=Clients,OU=MyCompany,
    DC=MyDomain,DC=LOCAL
DomainControllerServer = 在我的例子中的 IP 地址。 -- FQDN: MyDomain.LOCAL - 以句点分隔的 DC={part} 列表 |-- OU: 我的公司 |-- OU: 客户 |-- OU:Contoso |-- OU:金融网站 |-- OU:金融服务 |-- OU:用户

请记住使用反斜杠 (\) 转义无效字符,例如:+ , \ = /。

这是一场噩梦,但幸运的是它现在有效。

【问题讨论】:

标签: c# active-directory ldap


【解决方案1】:

您为用户 OU 提供的路径不是有效的 LDAP 路径。与您输入的文件系统路径或网络路径相比,LDAP 路径的构建方向相反。您的路径可能如下所示: ou=Users,ou=Financial Services,ou=Financial Site,ou=Contoso,ou=Clients,dc=MyCompany

前缀非常重要(即 ou= 或 dc=),如果任何对象属于不同的类,我提供的路径可能不正确。

我建议在原始代码示例的循环中打印 oResult.Path 并复制粘贴所需的路径。这样构建LDAP路径就不会出错了。

【讨论】:

  • 这就是我几乎的工作方式,肯定+1。但是我发现昨晚在 1 分钟到 5 点工作的路径字符串中缺少一个关键步骤!我使用的最终路径字符串是:LDAP://DomainControllerServer/OU=Users,OU=Financial Services,OU=Financial Site,OU=Contoso,OU=Clients,OU=MyCompany,DC=MyDomain,DC=LOCAL
  • 我会选择你作为答案,因为你是 100% 正确的,但我将编辑我的问题,以展示它在未来应该如何为其他人工作。希望其他人会发现这个问题有用!
  • “LDAP 路径是在相反的方向构造的”谢谢你,我很困惑为什么我得到一个不存在的错误。
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多