查询LDAP

35

我之前没有使用过LDAP,所以有点迷失。我需要连接到LDAP源,找到特定的属性并将其更改。程序的输入是一个包含用户列表的CSV文件。该程序应该从CSV文件中读取UID,找到LDAP记录并替换某个属性。我不知道如何做这件事。请问有人能指点我该怎么做吗?


3
以下文章可能会有用:使用.NET C# LDAP库 - Akram Shahda
1
由于您提到从CSV中读取UID,我感觉您可能没有连接到Active Directory LDAP存储库,因为通常您使用的LDAP属性是cn、name、distinguishedname、objectguid、objectsid、userprincipalname或samaccountname,而不是UID。因此,请更具体地说明您正在连接到什么以及您正在更改什么。还请告诉我们您需要连接到的“路径”或LDAP搜索根目录是什么。 - CosmosKey
1
如果您想使用LDS,另一个资源是ftp://ftp.ca.com/pub/ldap/docs/ldapv3/eTrust_LDAP_Server_Administrator_Guide_30.pdf。 - AA11oAKas
3个回答

27

@KenL 差点就骗到我了。我还得设置 DirectoryEntry 的 AuthenticationType 才能使它正常工作。此外,请注意你如何使用通配符 (Kleene Stars)。

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://some.ldap.server.com");
rootEntry.AuthenticationType = AuthenticationTypes.None; //Or whatever it need be
DirectorySearcher searcher = new DirectorySearcher(rootEntry);
var queryFormat = "(&(objectClass=user)(objectCategory=person)(|(SAMAccountName=*{0}*)(cn=*{0}*)(gn=*{0}*)(sn=*{0}*)(email=*{0}*)))";
searcher.Filter = string.Format(queryFormat, searchString);
foreach(SearchResult result in searcher.FindAll()) 
{
    Console.WriteLine("account name: {0}", result.Properties["samaccountname"].Count > 0 ? result.Properties["samaccountname"][0] : string.Empty);
    Console.WriteLine("common name: {0}", result.Properties["cn"].Count > 0 ? result.Properties["cn"][0] : string.Empty);
}

很棒的东西,这让我非常快速地上手了。顺便说一下:如果您无法匿名搜索,请使用DirectoryEntry类的替代构造函数进行绑定。 - sweetlilmre
2
Searchstring未定义,但除此之外,您的代码是复制粘贴的 :) - sonstabo

19

响应的第一个元素,使用 ADSI(老式)。

如何使用 C# 在 Active Directory 上通过 ADSI 实现几乎所有功能

响应的第二个元素,从 .NET 3.5 开始,Microsoft 引入了“Principal”和“AccountManagement”。

如何使用 C# 和 AccountManagement 在 Active Directory 上实现几乎所有功能

响应的第三个元素,您可以使用低级别(本机 LDAP)协议并结合System.DirectoryServices.Protocols (S.DS.P)

备注:如果您想了解如何从本机代码查询活动目录,可以查看 RFC 1823 中描述的 LDAP C 绑定 API。Microsoft 对其进行支持,请参见轻型目录访问协议 (LDAP) 的 MS 策略。您可以在Microsoft API in Lightweight Directory Access Protocol 的使用和参考手册中找到相关信息


13

从代码角度来看,它比您想象的要简单得多。您需要创建一个连接到目录的对象,设置搜索器,然后按属性名称进行搜索。

DirectoryEntry entry = new DirectoryEntry("LDAP://MyDomain.com");
DirectorySearcher dSearch = new DirectorySearcher(entry);
dSearch.Filter = "(&(objectCategory=person)(objectClass=user)(" + SType + "=" + Name + "))";

SType是类型名称,Name是实际用户名。


当单元测试成为一个关注点时,模拟DirectorySearcher是有问题的。 - Mario Tacke
@MarioTacke 通常不应该嘲笑一个数据结构 - 在更高的抽象层次上进行模拟,数据结构代码本身(在更高级别的模拟类型内部)通过集成测试。 - user2864740
1
但是你如何从dsearch中检索结果呢?我无法弄清楚如何查找用户是否被找到。 - Priyanka Arora

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接