using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.DirectoryServices; namespace OperateADLibrary { public class OperateAD { /// <summary> /// 域名 /// </summary> private string _domain; /// <summary> /// 主機域IP /// </summary> private string _domainIp; /// <summary> /// 管理員賬號 /// </summary> private string adminUser; /// <summary> /// 管理員密碼 /// </summary> private string adminPwd; /// <summary> /// 路徑的最前端 /// </summary> private string _ldapIdentity; /// <summary> /// 路徑的最后端 /// </summary> private string _suffixPath; #region 構造函數 /// <summary> /// 構造函數 /// 從webConfig的AppSettings屬性讀取值初始化字段 /// </summary> 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賬戶 /// <summary> /// 添加AD賬戶 /// </summary> /// <param name="organizeName">組織名稱</param> /// <param name="user">域賬戶</param> /// <returns>添加是否成功</returns> 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 重命名賬戶 /// <summary> /// 重命名賬戶 /// </summary> /// <param name="adminUser">管理員名稱</param> /// <param name="adminPassword">管理員密碼</param> /// <param name="oldUserName">原用戶名</param> /// <param name="newUserName">新用戶名</param> 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 設置用戶密碼 /// <summary> /// 設置用戶密碼 /// </summary> /// <param name="userName">用戶名</param> /// <param name="password">密碼</param> 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 修改密碼 /// <summary> /// 修改密碼 /// </summary> /// <param name="ude">用戶</param> /// <param name="password">舊密碼</param> /// <param name="password">新密碼</param> 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 刪除賬戶 /// <summary> /// 刪除AD賬戶,使用當前上下文的安全信息 /// </summary> /// <param name="userName">用戶名稱</param> 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 /// <summary> /// 創建OU /// </summary> /// <param name="adminName">管理員名稱</param> /// <param name="adminPassword">管理員密碼</param> /// <param name="name">創建的OU名稱</param> /// <param name="parentOrganizeUnit">父組織單位</param> /// <returns>目錄實體</returns> 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 /// <summary> /// 刪除OU /// </summary> /// <param name="name">創建的OU名稱</param> /// <param name="parentOrganizeUnit">父組織單位</param> /// <returns>目錄實體</returns> 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 創建組 /// <summary> /// 創建組 /// </summary> /// <param name="name">組名</param> /// <param name="OrganizeUnit">組織單位</param> /// <returns>是否創建成功</returns> 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 刪除組 /// <summary> /// 刪除組 /// </summary> /// <param name="name">組名</param> /// <param name="OrganizeUnit">組織單位</param> /// <returns>是否創建成功</returns> 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 將用戶加入到用戶組中 /// <summary> /// 將用戶加入到用戶組中 /// </summary> /// <param name="userName">用戶名</param> /// <param name="organizeName">組織名</param> /// <param name="groupName">組名</param> /// <param name="groupPath">組所在路徑</param> /// <exception cref="InvalidObjectException">用戶名或用戶組不存在</exception> 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 依據類別用戶名 查找目錄項 /// <summary> /// 查找目錄項 /// </summary> /// <param name="category">分類 users</param> /// <param name="name">用戶名</param> /// <returns>目錄項實體</returns> 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 獲取組織名稱路徑 /// <summary> /// 獲取組織名稱路徑 /// </summary> /// <param name="organizeUnit">組織</param> /// <returns></returns> public string GetOrganizeNamePath(string organizeUnit) { StringBuilder sb = new StringBuilder(); sb.Append(_ldapIdentity); return sb.Append(SplitOrganizeNameToDN(organizeUnit)).ToString(); } #endregion #region 分隔組織名稱為標准AD的DN名稱 /// <summary> /// 分隔組織名稱為標准AD的DN名稱,各個組織級別以"/"或"\"分開。如"總部/物業公司/小區",並且當前域為 /// bdxy.com,則返回的AD的DN表示名為"OU=小區,OU=物業公司,OU=總部,DC=bdxy,DC=com"。 /// </summary> /// <param name="organizeName">組織名稱</param> /// <returns>返回一個級別</returns> 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 獲取域路徑 /// <summary> /// 獲取域路徑 /// </summary> /// <returns>路徑</returns> public string GetDomainPath() { using (DirectoryEntry root = new DirectoryEntry(_ldapIdentity + _suffixPath, adminUser, adminPwd)) { return root.Path; } } #endregion #region 獲取Users容器的路徑 /// <summary> /// 獲取Users容器的下用戶的路徑 /// </summary> /// <param name="userName">用戶名</param> /// <returns></returns> 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路徑 /// <summary> /// 根據用戶所在的組織結構來構造用戶在AD中的DN路徑 /// </summary> /// <param name="userName">用戶名稱</param> /// <param name="organzieName">組織結構</param> /// <returns></returns> 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 啟用賬戶 /// <summary> /// 啟用賬戶 /// </summary> /// <param name="user"></param> 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 停用賬號 /// <summary> /// 停用賬號 /// </summary> /// <param name="user"></param> 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 判斷用戶是否已經存在域中 /// <summary> /// 判斷用戶是否已經存在域中 /// </summary> /// <param name="userName">用戶名</param> /// <returns></returns> 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 判斷域中是否存在組 /// <summary> /// 判斷域中是否存在組 /// </summary> /// <param name="groupName">組名</param> /// <returns></returns>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 判斷域中是否存在組織單位 /// <summary> /// 判斷域中是否存在組織單位 /// </summary> /// <param name="organizeName">組織單位名</param> /// <returns></returns> 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 獲取域用戶信息 /// <summary> /// 獲取域用戶信息 /// </summary> /// <param name="path">目錄</param> /// <param name="username">用戶名</param> /// <returns></returns> 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 從域中按照用戶名查找用戶 /// <summary> /// 從域中按照用戶名查找用戶 /// </summary> /// <param name="path">路徑</param> /// <param name="AdUser">管理員賬戶</param> /// <param name="AdPwd">管理員密碼</param> /// <param name="username">用戶名</param> /// <returns></returns> 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域查詢 /// <summary> /// 查尋用戶信息 /// </summary> /// <param name="userName">用戶名</param> private List<string> AccsesADQuery(string userName) { //定義de進入AD架構 DirectoryEntry de = new DirectoryEntry(GetDomainPath(), adminUser, adminPwd); //定義ds查找AD DirectorySearcher ds = new DirectorySearcher(de); string value = string.Empty; List<string> domainList = new List<string>(); 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 } }