LDAP 协议:LDAP的英文全称是Lightweight Directory Access Protocol,即轻量级目录访问协议.
为了能对LDAP协议进行更好的理解,我们需要对以下概念有初步的认识:
目录:Directory,存放对象的信息,这些信息以某种顺序组织,详细描述每个对象.
目录信息树:DIT,Directory Information Tree,目录条目的集合构成了目录信息树.
条目:Entry,目录信息树中的一个结点,是对象信息的集合,是目录信息中最基本的单位,包含该对象的一系列属性.
属性:Attribute,属性描述对象的特征.一个属性由属性类型(type)和一个或多个属性值(values)构成.
相对标识名:RDN,Relative Distinguished Name,条目的名字.
唯一标识名:DN,Distinguished Name,在一个目录信息树中唯一标识一个条目的名字.
Active Directory :Active Directory是指Windows 2000网络中的目录服务。
.Net Framework 2.0中涉及 AD编程的两个主要的类。
- System.DirectoryServices.DirectoryEntry
- System.DirectoryServices.DirectorySearcher
编程关键步骤:
- 连接AD
Code
1using (DirectoryEntry de = new DirectoryEntry())
2 {
3 de.Path = "LDAP://training.local/DC=training,DC=local";
4 de.Username = "admin@TRAINING";
5 de.Password = "123123";
6 }
- 访问AD中的节点
Visit the AD Node
DirectorySearcher NewSearch = new DirectorySearcher(de);
NewSearch.Filter = "(objectClass=user)";
NewSearch.SearchScope = SearchScope.Subtree;
NewSearch.PropertiesToLoad.Add("name");
NewSearch.PropertiesToLoad.Add("description");
NewSearch.PropertiesToLoad.Add("distinguishedName");
NewSearch.PropertiesToLoad.Add("extensionAttribute15");
NewSearch.Sort = new SortOption("description", SortDirection.Ascending);
SearchResultCollection results = NewSearch.FindAll();
foreach (SearchResult sr in results)
{
DirectoryEntry myde = sr.GetDirectoryEntry();
string Emp_number = myde.Properties["description"].Value.ToString();
.
.
.
}
- 给AD节点属性赋值
Write value
1 if (!de.Properties.Contains("telephoneNumber"))
2 {
3 de.Properties["telephoneNumber"].Add(dr["p_busphone"].ToString().Trim());
4 }
5 else
6 {
7 de.Properties["telephoneNumber"].Value = dr["p_busphone"].ToString().Trim();
8 }
- 定时启动windows service
Code
1if(System.DateTime.Now.ToString().EndsWith("00:00:00"))
2
3{
4
5 //Add your code here
6
7}
工具:adsiedit.msc 查看AD中的节点的属性。
也可以通过以下的代码获取属性节点。(但只能获取存在赋值的属性列表)直接访问未赋值的属性会抛出异常。
Code
1PropertyCollection properties = de.Properties;
2
3foreach (string name in properties.PropertyNames)
4
5{
6
7 foreach (object o in properties[name])
8
9 {
10
11Console.WriteLine(name + ": " + o.ToString());
12
13 }
14
15}
1PropertyCollection properties = de.Properties;
2
3foreach (string name in properties.PropertyNames)
4
5{
6
7 foreach (object o in properties[name])
8
9 {
10
11Console.WriteLine(name + ": " + o.ToString());
12
13 }
14
15}
日志管理:
EventLog
Code
1if (!System.Diagnostics.EventLog.SourceExists("ADLogSourse"))
2 {
3 System.Diagnostics.EventLog.CreateEventSource("ADLogSourse", "ADLog");
4 }
5 MyEventLog.Source = "ADLogSourse";
6 MyEventLog.Log = "ADLog";可以通过windows自带的日志查看工具查看。