日期:2014-05-17 浏览次数:20952 次
.net对ladp操作windowsAD的一些类和接口,都放在System.DirectoryServices命名空间下面。
?
public void CreateWindowsUser(String userName,String password,String userDesc,int userControl)
{
String ladpRootPath = "LDAP://192.168.213.168/CN=Users,DC=pk1,DC=cctv,DC=com";
DirectoryEntry ladpRoot = new DirectoryEntry(ladpRootPath);
ladpRoot.Username = "XXXXX";
ladpRoot.Password = "XXXXX";
DirectoryEntry user = ladpRoot.Children.Add("CN="+ userName, "user");
user.Properties["sAMAccountName"].Value = userName;
user.Properties["description"].Value = userDesc;
user.Properties["userAccountControl"].Value = userControl;
user.CommitChanges();
user.Invoke("SetPassword", password);
user.CommitChanges();
user.Close();
}
?
上述方法简单实现了添加一个Windows用户,值得注意的是如果你的程序是放在域控上面执行的,那么 ladpRoot.Username和ladpRoot.Password就不能赋值。另外ladpRootPath是ladp的路径写法,LDAP://192.168.213.168表示你要操作的主机地址,?DC=pk1,DC=cctv,DC=com表示要操作的Windows域,CN=Users表示在windows域的主目录下的Users容器对象。方法参数userControl表示一些用户属性,如密码永不过期,禁用用户等等,具体的值,详见http://support.microsoft.com/kb/305144/zh-cn,如果用户包含多个属性,则将这些属性值做按位或(|)的运算即可。在这些用户属性中,有一个比较例外,那就是PASSWD_CANT_CHANGE,此属性表示用户不能修改密码,但是他是一个只读的属性,也就是说不能通过设置userAccountControl来实现功能,如果要实现此功能,那么必须在上述代码 user.Close();之前插入如下代码:
?
Guid changePasswordGuid = new Guid("{ab721a53-1e2f-11d0-9819-00aa0040529b}");
IdentityReference selfSddl = new SecurityIdentifier(WellKnownSidType.SelfSid, null);
IdentityReference everyoneSddl = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
ActiveDirectoryAccessRule selfAccRule = new ActiveDirectoryAccessRule(selfSddl, ActiveDirectoryRights.ExtendedRight, AccessControlType.Deny, changePasswordGuid);
ActiveDirectoryAccessRule everyoneAccRule = new ActiveDirectoryAccessRule(everyoneSddl, ActiveDirectoryRights.ExtendedRight, AccessControlType.Deny, changePasswordGuid);
user.ObjectSecurity.AddAccessRule(selfAccRule);
user.ObjectSecurity.AddAccessRule(everyoneAccRule);
user.CommitChanges();
?
下面给出一些常用的用户操作代码:
?
修改用户:
?
public void ModifyWindowsUser(String userName,String password,String userDesc,int userControl)
{
String ladpRootPath = "LDAP://192.168.213.168/CN=Users,DC=pk1,DC=cctv,DC=com";
DirectoryEntry ladpRoot = new DirectoryEntry(ladpRootPath);
ladpRoot.Username = "XXXXX";
ladpRoot.Password = "XXXXX";
DirectoryEntry user = ladpRoot.Children.Find("CN=" +userName, "user");
user.Properties["description"].Value = userDesc;
user.Properties["userAccountControl"].Value = userControl;
user.CommitChanges();
user.Invoke("SetPassword", password);
user.CommitChanges();
user.Close();
}
?
?
删除用户
?
?
public void DeleteWindowsUser(String userName)
{
String ladpRootPath = "LDAP://192.168.213.168/CN=Users,DC=pk1,DC=cctv,DC=com";
DirectoryEntry ladpRoot = new DirectoryEntry(ladpRootPath);
ladpRoot.Username = "XXXXX";
ladpRoot.Password = "XXXXX";
DirectoryEntry user = ladpRoot.Children.Find("CN=" +userName, "user");
user.DeleteTree();
user.Close();
}
?
?
?
?
?
?
?
?
?