博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.net操作AD域
阅读量:5091 次
发布时间:2019-06-13

本文共 27822 字,大约阅读时间需要 92 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;using System.DirectoryServices;namespace OperateADLibrary{    public class OperateAD    {        ///         /// 域名        ///         private string _domain;        ///         /// 主机域IP        ///         private string _domainIp;        ///         /// 管理员账号        ///         private string adminUser;        ///         /// 管理员密码        ///         private string adminPwd;        ///         /// 路径的最前端        ///         private string _ldapIdentity;        ///         /// 路径的最后端        ///         private string _suffixPath;        #region 构造函数        ///         /// 构造函数        /// 从webConfig的AppSettings属性读取值初始化字段        ///         public OperateAD(string domain, string domainIp, string adUser, string adPwd)        {            //_domain = System.Configuration.ConfigurationManager.AppSettings["Domain"].ToString();            //_domainIp = System.Configuration.ConfigurationManager.AppSettings["DomainIp"].ToString();            //adminUser = System.Configuration.ConfigurationManager.AppSettings["ADAdminUser"].ToString();            //adminPwd = System.Configuration.ConfigurationManager.AppSettings["ADAdminPassword"].ToString();            //_ldapIdentity = "LDAP://" + _domainIp + "/";            //_suffixPath = "DC=" + _domain + ",DC=COM";            //_domain = "bdxy";            //_domainIp = "10.1.209.197";            //adminUser = "administrator";            //adminPwd = "123456";            _domain = domain;            _domainIp = domainIp;            adminUser = adUser;            adminPwd = adPwd;            _ldapIdentity = "LDAP://" + _domainIp + "/";            _suffixPath = "DC=" + _domain + ",DC=com";        }        #endregion        #region 组织结构下添加AD账户        ///         /// 添加AD账户        ///         /// 组织名称        /// 域账户        /// 
添加是否成功
public bool AddADAccount(string organizeName, DomainUser user) { DirectoryEntry entry = null; try { if (ExitOU(organizeName) && user != null) { entry = new DirectoryEntry(GetOrganizeNamePath(organizeName), adminUser, adminPwd, AuthenticationTypes.Secure); //增加账户到域中 DirectoryEntry NewUser = entry.Children.Add("CN=" + user.UserName, "user"); NewUser.Properties["sAMAccountName"].Add(user.UserName); //account NewUser.Properties["userPrincipalName"].Value = user.UserPrincipalName; //user logon name,xxx@bdxy.com NewUser.Properties["givenName"].Value = "New User";//名 NewUser.Properties["initials"].Value = "Ms"; NewUser.Properties["name"].Value = "12";//full name NewUser.Properties["sn"].Value = user.UserId; NewUser.Properties["displayName"].Value = user.UserName; NewUser.Properties["company"].Value = "1234"; NewUser.Properties["physicalDeliveryOfficeName"].Value = user.PhysicalDeliveryOfficeName; NewUser.Properties["Department"].Value = user.Department; if (user.Telephone != null && user.Telephone != "") { NewUser.Properties["telephoneNumber"].Value = user.Telephone; } if (user.Email != null && user.Email != "") { NewUser.Properties["mail"].Value = user.Email; } if (user.Description != null && user.Description != "") { NewUser.Properties["description"].Value = user.Description; } NewUser.CommitChanges(); //设置密码 //反射调用修改密码的方法(注意端口号的问题 端口号会引起方法调用异常) NewUser.Invoke("SetPassword", new object[] { user.UserPwd }); //默认设置新增账户启用 NewUser.Properties["userAccountControl"].Value = 0x200; NewUser.CommitChanges(); //DomainUser._success = "账户添加成功!"; return true; } else { //DomainUser._failed = "在域中不存在直属组织单位"; return false; } } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { //DomainUser._failed = "账户添加失败!"+ex.Message.ToString(); return false; } finally { if (entry != null) { entry.Dispose(); } } } #endregion #region 重命名账户 /// /// 重命名账户 /// /// 管理员名称 /// 管理员密码 /// 原用户名 /// 新用户名 public bool RenameUser(string oldUserName, string newUserName) { try { DirectoryEntry userEntry = FindObject("user", oldUserName); if (userEntry != null) { userEntry.Rename("CN="+newUserName); userEntry.CommitChanges(); //DomainUser._success = "重命名成功!"; return true; } //DomainUser._failed = "没找到用户!" + oldUserName; return false; } catch (Exception ex) { //DomainUser._failed = "重命名失败!"+ex.Message.ToString(); return false; } } #endregion #region 设置用户密码 /// /// 设置用户密码 /// /// 用户名 /// 密码 public bool SetUserPassword(string userName, string password) { try { DirectoryEntry userEntry = FindObject("user", userName); if (userEntry != null) { userEntry.Invoke("SetPassword", new object[] { password }); userEntry.CommitChanges(); //DomainUser._success = "密码设置成功!"; return true; } //DomainUser._failed = "没找到用户!" + userName; return false; } catch (Exception ex) { //DomainUser._failed = "密码设置失败!"+ex.Message.ToString(); return false; } } #endregion #region 修改密码 /// /// 修改密码 /// /// 用户 /// 旧密码 /// 新密码 public bool ChangePassword(string username, string oldpwd, string newpwd) { try { DirectoryEntry entry = FindObject("user", username); if (entry != null) { // to-do: 需要解决密码策略问题 entry.Invoke("ChangePassword", new object[] {oldpwd, newpwd }); entry.CommitChanges(); entry.Close(); // DomainUser._success = "密码修改成功!"; return true; } else { // DomainUser._failed = "没找到用户!" + username; return false; } } catch (Exception ex) { //DomainUser._failed = "密码修改失败!"+ex.Message.ToString(); return false; } } #endregion #region 删除账户 /// /// 删除AD账户,使用当前上下文的安全信息 /// /// 用户名称 public bool DeleteADAccount(string userName) { try { DirectoryEntry user = FindObject("user", userName); if (user != null) { using (DirectoryEntry de = new DirectoryEntry(user.Parent.Path, adminUser, adminPwd)) { de.Children.Remove(user); de.CommitChanges(); //DomainUser._success = "账户删除成功!"; return true; } } // DomainUser._failed = "未找到账户!"; return false; } catch (Exception ex) { //DomainUser._failed = "账户删除失败!" + ex.Message.ToString(); return false; } } #endregion

 

 

#region 创建OU        ///         /// 创建OU        ///         /// 管理员名称        /// 管理员密码        /// 创建的OU名称        /// 父组织单位        /// 
目录实体
public DirectoryEntry CreateOrganizeUnit(string name, string parentOrganizeUnit) { DirectoryEntry parentEntry = null; try { //示例顶级"" parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit), adminUser, adminPwd, AuthenticationTypes.Secure); DirectoryEntry organizeEntry = parentEntry.Children.Add("OU=" + name, "organizationalUnit"); organizeEntry.CommitChanges(); //DomainUser._success = "组织单位添加成功!"; return organizeEntry; } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { //DomainUser._failed = "添加组织单位失败!"+ex.Message.ToString(); return new DirectoryEntry(); } finally { if (parentEntry != null) { parentEntry.Dispose(); } } } #endregion #region 删除OU /// /// 删除OU /// /// 创建的OU名称 /// 父组织单位 ///
目录实体
public bool DeleteOrganizeUnit(string name, string parentOrganizeUnit) { DirectoryEntry parentEntry = null; try { //示例顶级"" parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit), adminUser, adminPwd, AuthenticationTypes.Secure); DirectoryEntry organizeEntry = parentEntry.Children.Find("OU=" + name, "organizationalUnit"); //先删除组织单元下的用户或者组 parentEntry.Children.Remove(organizeEntry); organizeEntry.CommitChanges(); //DomainUser._success = "组织单位删除成功!"; return true; } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { //DomainUser._failed = "组织单位删除失败!"+ex.Message.ToString(); return false; } finally { if (parentEntry != null) { parentEntry.Dispose(); } } } #endregion #region 创建组 /// /// 创建组 /// /// 组名 /// 组织单位 ///
是否创建成功
public bool CreateGroup(string name, string OrganizeUnit) { DirectoryEntry parentEntry = null; try { parentEntry = new DirectoryEntry(GetOrganizeNamePath(OrganizeUnit), adminUser, adminPwd, AuthenticationTypes.Secure); DirectoryEntry groupEntry = parentEntry.Children.Add("CN=" + name, "group"); groupEntry.CommitChanges(); // DomainUser._success = "组创建成功!"; return true; } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { //DomainUser._failed = "组创建失败!"+ex.Message.ToString(); return false; } finally { if (parentEntry != null) { parentEntry.Dispose(); } } } #endregion #region 删除组 /// /// 删除组 /// /// 组名 /// 组织单位 ///
是否创建成功
public bool DeleteGroup(string name, string OrganizeUnit) { DirectoryEntry parentEntry = null; try { parentEntry = new DirectoryEntry(GetOrganizeNamePath(OrganizeUnit), adminUser, adminPwd, AuthenticationTypes.Secure); DirectoryEntry groupEntry = parentEntry.Children.Find("CN=" + name, "group"); parentEntry.Children.Remove(groupEntry); groupEntry.CommitChanges(); //DomainUser._success = "组删除成功!"; return true; } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { // DomainUser._failed = "组删除失败!" + ex.Message.ToString(); return false; } finally { if (parentEntry != null) { parentEntry.Dispose(); } } } #endregion #region 将用户加入到用户组中 /// /// 将用户加入到用户组中 /// /// 用户名 /// 组织名 /// 组名 /// 组所在路径 ///
用户名或用户组不存在
public bool AddUserToGroup(string userName, string groupName, string groupPath) { DirectoryEntry group = null; DirectoryEntry user = null; try { group = ExitGroup(groupName, groupPath); user = ExitUser(userName); if ((group != null) && (user != null)) { //加入用户到用户组中 group.Properties["member"].Add(user.Properties["distinguishedName"].Value); group.CommitChanges(); //DomainUser._success = "用户成功加入组!"; return true; } else { return false; } } catch (Exception ex) { //DomainUser._failed = "加入组失败!"+ex.Message.ToString(); return false; } } #endregion #region 依据类别用户名 查找目录项 /// /// 查找目录项 /// /// 分类 users /// 用户名 ///
目录项实体
public DirectoryEntry FindObject(string category, string name) { DirectoryEntry de = null; DirectorySearcher ds = null; DirectoryEntry userEntry = null; try { de = new DirectoryEntry(GetDomainPath(), adminUser, adminPwd, AuthenticationTypes.Secure); ds = new DirectorySearcher(de); string queryFilter = string.Format("(&(objectCategory=" + category + ")(sAMAccountName={0}))", name); ds.Filter = queryFilter; ds.Sort.PropertyName = "cn"; SearchResult sr = ds.FindOne(); if (sr != null) { userEntry = sr.GetDirectoryEntry(); } return userEntry; } catch (Exception ex) { //DomainUser._failed = ex.Message.ToString(); return new DirectoryEntry(); } finally { if (ds != null) { ds.Dispose(); } if (de != null) { de.Dispose(); } } } #endregion #region 获取组织名称路径 /// /// 获取组织名称路径 /// /// 组织 ///
public string GetOrganizeNamePath(string organizeUnit) { StringBuilder sb = new StringBuilder(); sb.Append(_ldapIdentity); return sb.Append(SplitOrganizeNameToDN(organizeUnit)).ToString(); } #endregion #region 分隔组织名称为标准AD的DN名称 /// /// 分隔组织名称为标准AD的DN名称,各个组织级别以"/"或"\"分开。如"总部/物业公司/小区",并且当前域为 /// bdxy.com,则返回的AD的DN表示名为"OU=小区,OU=物业公司,OU=总部,DC=bdxy,DC=com"。 /// /// 组织名称 ///
返回一个级别
public string SplitOrganizeNameToDN(string organizeName) { StringBuilder sb = new StringBuilder(); if (organizeName.Equals("Users") || string.IsNullOrEmpty(organizeName)) { sb.Append("CN=Users,").Append(_suffixPath); return sb.ToString(); } else { if (organizeName != null && organizeName.Length > 0) { string[] allOu = organizeName.Split(new char[] { '/', '\\' }); for (int i = allOu.Length - 1; i >= 0; i--) { string ou = allOu[i]; if (sb.Length > 0) { sb.Append(","); } sb.Append("OU=").Append(ou); } } //如果传入了组织名称,则添加, if (sb.Length > 0) { sb.Append(","); } sb.Append(_suffixPath); return sb.ToString(); } } #endregion #region 获取域路径 /// /// 获取域路径 /// ///
路径
public string GetDomainPath() { using (DirectoryEntry root = new DirectoryEntry(_ldapIdentity + _suffixPath, adminUser, adminPwd)) { return root.Path; } } #endregion #region 获取Users容器的路径 /// /// 获取Users容器的下用户的路径 /// /// 用户名 ///
private string GetUserPath(string userName) { StringBuilder sb = new StringBuilder(); sb.Append(_ldapIdentity); if (userName != null && userName.Length > 0) { sb.Append("CN=").Append(userName).Append(","); } sb.Append("CN=Users,").Append(_suffixPath); return sb.ToString(); } #endregion #region 根据用户所在的组织结构来构造用户在AD中的DN路径 /// /// 根据用户所在的组织结构来构造用户在AD中的DN路径 /// /// 用户名称 /// 组织结构 ///
public string GetUserPath(string userName, string organzieName) { StringBuilder sb = new StringBuilder(); sb.Append(_ldapIdentity); sb.Append("CN=").Append(userName).Append(",").Append(SplitOrganizeNameToDN(organzieName)); return sb.ToString(); } #endregion

 

#region 启用账户        ///         /// 启用账户        ///         ///         public bool EnableAccount(string userName)        {            try            {                DirectoryEntry userEntry = FindObject("user", userName);                int val = (int)userEntry.Properties["userAccountControl"].Value;                userEntry.Properties["userAccountControl"].Value = val & ~0x2;                userEntry.CommitChanges();                userEntry.Close();                //DomainUser._success = "启用账户成功!";                return true;            }            catch (Exception ex)            {                //DomainUser._failed = ex.Message.ToString();                return false;            }        }        #endregion        #region 停用账号        ///         /// 停用账号        ///         ///         public  bool DisableAccount(string userName)        {            try            {                DirectoryEntry userEntry = FindObject("user", userName);                userEntry.Properties["userAccountControl"].Value = 0x2;                userEntry.CommitChanges();                userEntry.Close();                //DomainUser._success = "停用账户成功!";                return true;            }            catch (System.DirectoryServices.DirectoryServicesCOMException ex)            {                //DomainUser._failed = ex.Message.ToString();                return false;            }        }        #endregion        #region 判断用户是否已经存在域中        ///         /// 判断用户是否已经存在域中        ///         /// 用户名        /// 
private DirectoryEntry ExitUser(string userName) { try { DirectoryEntry de = null; de = FindObject("user", userName); if (de == null) { return new DirectoryEntry(); ; } else { return de; } } catch (Exception ex) { //DomainUser._failed = ex.Message.ToString(); return new DirectoryEntry(); } } #endregion #region 判断域中是否存在组 /// /// 判断域中是否存在组 /// /// 组名 ///
lan private DirectoryEntry ExitGroup(string groupName, string groupPath) { DirectoryEntry rootUser = null; DirectoryEntry group = null; try { string path = GetOrganizeNamePath(groupPath); rootUser = new DirectoryEntry(path, adminUser, adminPwd, AuthenticationTypes.Secure); group = rootUser.Children.Find("CN=" + groupName); if (group != null) { return group; } return new DirectoryEntry(); } catch (Exception ex) { // DomainUser._failed = ex.Message.ToString() + "在域中不存在组“" + groupName + "”或路组织单位不正确"; return new DirectoryEntry(); } } #endregion #region 判断域中是否存在组织单位 /// /// 判断域中是否存在组织单位 /// /// 组织单位名 ///
private bool ExitOU(string organizeName) { DirectoryEntry rootUser = null; DirectoryEntry ouFind = null; if (string.IsNullOrEmpty(organizeName)) { return true; } else { //分解路径 string[] allOu = organizeName.Split(new char[] { '/' }); //获取直属部门 string OUName = allOu[allOu.Length - 1].ToString(); try { string path = GetOrganizeNamePath(organizeName); rootUser = new DirectoryEntry(path, adminUser, adminPwd, AuthenticationTypes.Secure); ouFind = rootUser.Parent.Children.Find("OU=" + OUName); if (ouFind != null) { return true; } return false; } catch (Exception ex) { //DomainUser._failed = ex.Message.ToString() + "在域中不存在组织单位“" + OUName + "”"; return false; } } } #endregion #region 获取域用户信息 /// /// 获取域用户信息 /// /// 目录 /// 用户名 ///
public DomainUser GetAdUserInfo(string userName) { DomainUser du = new DomainUser(); DirectoryEntry de = FindObject("user", userName); if (de != null) { if (de.Properties["samAccountName"].Value != null) { du.UserId = de.Properties["samAccountName"].Value.ToString(); } if (de.Properties["displayName"].Value != null) { du.UserName = de.Properties["displayName"].Value.ToString(); } if (de.Properties["userPrincipalName"].Value != null) { du.UserPrincipalName = de.Properties["userPrincipalName"].Value.ToString(); } if (de.Properties["telephoneNumber"].Value != null) { du.Telephone = de.Properties["telephoneNumber"].Value.ToString(); } if (de.Properties["mail"].Value != null) { du.Email = de.Properties["mail"].Value.ToString(); } if (de.Properties["description"].Value != null) { du.Description = de.Properties["description"].Value.ToString(); } if (de.Properties["Department"].Value != null) { du.Department = de.Properties["Department"].Value.ToString(); } } return du; } #endregion #region 从域中按照用户名查找用户 /// /// 从域中按照用户名查找用户 /// /// 路径 /// 管理员账户 /// 管理员密码 /// 用户名 ///
private DirectoryEntry GetUser(string path, string username) { DirectoryEntry deuser; try { DirectoryEntry de = new DirectoryEntry(path, adminUser, adminPwd); DirectorySearcher deSearch = new DirectorySearcher(de); deSearch.Filter = "(&(objectClass=user)(cn=" + username + "))"; deSearch.SearchScope = SearchScope.Subtree; SearchResult result = deSearch.FindOne(); if (result != null) { deuser = result.GetDirectoryEntry(); return deuser; } else { return null; } } catch (Exception ex) { //DomainUser._failed = ex.Message.ToString(); return null; } } #endregion #region 进入AD域查询 /// /// 查寻用户信息 /// /// 用户名 private List
AccsesADQuery(string userName) { //定义de进入AD架构 DirectoryEntry de = new DirectoryEntry(GetDomainPath(), adminUser, adminPwd); //定义ds查找AD DirectorySearcher ds = new DirectorySearcher(de); string value = string.Empty; List
domainList = new List
(); try { //3.定义查询 ds.Filter = "(SAMAccountName=" + userName + ")"; ds.PropertiesToLoad.Add("SAMAccountName");//account ds.PropertiesToLoad.Add("Name");//full name ds.PropertiesToLoad.Add("displayName"); ds.PropertiesToLoad.Add("mail"); ds.PropertiesToLoad.Add("sn"); ds.PropertiesToLoad.Add("description"); ds.PropertiesToLoad.Add("Department"); ds.PropertiesToLoad.Add("userPrincipalName");//user logon name,xxx@bdxy.com ds.PropertiesToLoad.Add("physicalDeliveryOfficeName"); ds.PropertiesToLoad.Add("telephoneNumber"); //查找一个 SearchResult sr = ds.FindOne(); if (sr != null) { //列出值 foreach (string key in sr.Properties.PropertyNames) { foreach (object obj in de.Properties[key]) { value += key + " = " + obj + Environment.NewLine; domainList.Add(value); } } return domainList; } else { return domainList; } } catch (Exception ex) { //DomainUser._failed = ex.Message.ToString(); return domainList; } finally { if (ds != null) { ds.Dispose(); } if (de != null) { de.Dispose(); } } } #endregion }}

 

转载于:https://www.cnblogs.com/VicHuang/p/3753555.html

你可能感兴趣的文章
.NET环境下,通过LINQ操作SQLite数据库
查看>>
Python day 6(4) Python 函数式编程2
查看>>
面向对象 的属性 类方法 静态方法
查看>>
python split()函数多个分隔符用法
查看>>
读书笔记--Spring Integration in Action 目录
查看>>
Linux console text color
查看>>
ES6 Promise对象then方法链式调用
查看>>
LiveNVR RTSP流媒体服器软件通过按需直播降低企业服务带宽 - RTSP网页无插件直播...
查看>>
css正常文档布局和元素可见性代码
查看>>
JS --实用小方法收集
查看>>
python-数据类型
查看>>
ASP.NET EF实体主外键关系
查看>>
【python之路15】深浅拷贝及函数
查看>>
Python操作RabbitMQ
查看>>
HDUOJ----4509湫湫系列故事——减肥记II
查看>>
linux下mysql函数的详细案列
查看>>
【2019.7.24】数颜色 / 聪明的可可 / 奖章分发
查看>>
深度学习基础网络 ResNet
查看>>
js(事件) d3
查看>>
算法学习-带分数
查看>>