AD域操作帮助类

 写于2015年9月,今天整理历史代码找到,上传备份并标记需要优化。

域里面的信息都是可编辑的属性,域操作实际就是对属性的操作。只要知道每个属性对应的内容,该如何操作,就能找到方法获得或者修改想要的信息。

public class ADHelper
    {
        private static string _path = ConfigurationManager.AppSettings["AdHostPath"];//
        private static string _dnPath = ConfigurationManager.AppSettings["AdPath"];
        private static string AdminName = ConfigurationManager.AppSettings["AdminName"];
        private static string AdminPwd = ConfigurationManager.AppSettings["AdminPwd"];

        //userAccountControl
        //private static readonly int SCRIPT = 0x0001; //将运行登录脚本
        private static readonly int ACCOUNTDISABLE = 0x0002;//禁用用户帐户
        //private static readonly int HOMEDIR_REQUIRED = 0x0008;//需要主文件夹
        //private static readonly int LOCKOUT = 0x0010;
        //private static readonly int PASSWD_NOTREQD = 0x0020;//不需要密码
        //private static readonly int PASSWD_CANT_CHANGE = 0x0040;//用户不能更改密码。可以读取此标志,但不能直接设置它。
        //private static readonly int ENCRYPTED_TEXT_PWD_ALLOWED = 0x0080;//用户可以发送加密的密码
        //private static readonly int TEMP_DUPLICATE_ACCOUNT = 0x0100;/*此帐户属于其主帐户位于另一个域中的用户。
        //            此帐户为用户提供访问该域的权限,但不提供访问信任该域的任何域的权限。有时将这种帐户称为“本地用户帐户”。*/
        private static readonly int NORMAL_ACCOUNT = 0x0200;//典型用户的默认帐户类型
        //private static readonly int INTERDOMAIN_TRUST_ACCOUNT = 0x0800;// 对于信任其他域的系统域,此属性允许信任该系统域的帐户。
        //private static readonly int WORKSTATION_TRUST_ACCOUNT = 0x1000;/*这是运行 Microsoft Windows NT 4.0 Workstation、
        //            Microsoft Windows NT 4.0 Server、Microsoft Windows 2000 Professional 或 Windows 2000 Server 并且属于该域的计算机的计算机帐户。*/
        //private static readonly int SERVER_TRUST_ACCOUNT = 0x2000;//属于该域的域控制器的计算机帐户
        private static readonly int DONT_EXPIRE_PASSWORD = 0x10000;//该帐户上永远不会过期的密码
        //private static readonly int MNS_LOGON_ACCOUNT = 0x20000;//MNS 登录帐户
        //private static readonly int SMARTCARD_REQUIRED = 0x40000;//强制用户使用智能卡登录
        //private static readonly int TRUSTED_FOR_DELEGATION = 0x80000;/*设置此标志后,将信任运行服务的服务帐户(用户或计算机帐户)进行 Kerberos 委派。
        //            任何此类服务都可模拟请求该服务的客户端。若要允许服务进行 Kerberos 委派,必须在服务帐户的userAccountControl 属性上设置此标志。*/
        //private static readonly int NOT_DELEGATED = 0x100000;//设置此标志后,即使将服务帐户设置为信任其进行 Kerberos 委派,也不会将用户的安全上下文委派给该服务。
        //private static readonly int USE_DES_KEY_ONLY = 0x200000;//(Windows 2000/Windows Server 2003) 将此用户限制为仅使用数据加密标准 (DES) 加密类型的密钥。
        //private static readonly int DONT_REQ_PREAUTH = 0x400000;//(Windows 2000/Windows Server 2003) 此帐户在登录时不需要进行 Kerberos 预先验证。
        //private static readonly int PASSWORD_EXPIRED = 0x800000;//(Windows 2000/Windows Server 2003) 用户的密码已过期
        //private static readonly int TRUSTED_TO_AUTH_FOR_DELEGATION = 0x1000000;/*(Windows 2000/Windows Server 2003) 允许该帐户进行委派。
        //            这是一个与安全相关的设置。应严格控制启用此选项的帐户。此设置允许该帐户运行的服务冒充客户端的身份,并作为该用户接受网络上其他远程服务器的身份验证*/

        //group 
        private static readonly int GROUP_TYPE = 0x0008;//unisersal group

        /// <summary>
        /// 获取所有AD账户
        /// </summary>
        /// <returns></returns>
        public static List<ADUser> GetAllAdUsers()
        {
            DirectoryEntry de = new DirectoryEntry(_path + _dnPath, AdminName, AdminPwd);
            DirectorySearcher searcher = new DirectorySearcher(de, "(&(objectCategory=user)(sAMAccountName=*))");
            SearchResultCollection src = searcher.FindAll();
            List<ADUser> list = new List<ADUser>();
            foreach (SearchResult result in src)
            {
                if (result != null)
                {
                    DirectoryEntry entry = result.GetDirectoryEntry();
                    if (entry == null)
                    {
                        continue;
                    }
                    string n = (entry.Properties["distinguishedName"].Value == null) ? string.Empty : entry.Properties["distinguishedName"].Value.ToString();
                    if (n.IndexOf("OU") != -1)
                    {
                        string ADAccount = entry.Properties["sAMAccountName"].Value.ToString();
                        string DisplayName = (entry.Properties["displayName"].Value == null) ? "" : entry.Properties["displayName"].Value.ToString();
                        //var fileTime = (entry.Properties["Lastlogon"][0] as long?).GetValueOrDefault();
                        var Email = (entry.Properties["Email"].Value == null) ? "" : entry.Properties["Email"].Value.ToString();
                        var createTime = entry.Properties["whenCreated"].Value;
                        LargeInteger largeInt = (LargeInteger)entry.Properties["Lastlogon"][0];
                        long liTicks = largeInt.HighPart * 0x100000000 + largeInt.LowPart;
                        //long fileTime = lastLogon==0?entry.Properties[""]
                        ADUser user = new ADUser { AdAccount = ADAccount, LastLogonTime = liTicks == 0 ? Convert.ToDateTime(createTime) : DateTime.FromFileTime(liTicks), DisplayName = DisplayName };
                        list.Add(user);
                    }
                    entry.Dispose();
                    entry.Close();
                }
            }
            de.Dispose();
            de.Close();
            return list;
        }

        #region GetProperty

        /// <summary>
        /// 获取属性值
        /// </summary>
        /// <param name="de"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetProperty(DirectoryEntry de, string propertyName)
        {
            if (de.Properties.Contains(propertyName))
            {
                return de.Properties[propertyName].Value.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获得指定搜索结果中指定属性名对应的值
        /// </summary>
        /// <param name="searchResult"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetProperty(SearchResult searchResult, string propertyName)
        {
            if (searchResult.Properties.Contains(propertyName))
            {
                return searchResult.Properties[propertyName][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion

        #region GetDirectoryObject

        /// <summary>
        /// 获得DirectoryEntry对象实例,以管理员登陆AD
        /// </summary>
        /// <returns></returns>
        private static DirectoryEntry GetDirectoryObject()
        {
            DirectoryEntry entry = new DirectoryEntry(_path + _dnPath, AdminName, AdminPwd, AuthenticationTypes.Secure);
            return entry;
        }

        /// <summary>
        ///  获得指定路径path的DirectoryEntry对象实例,以管理员登陆AD
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static DirectoryEntry GetDirectoryObject(string path)
        {
            DirectoryEntry entry = new DirectoryEntry(path, AdminName, AdminPwd, AuthenticationTypes.Secure);
            return entry;
        }

        /// <summary>
        /// 根据指定用户名和密码获得相应DirectoryEntry实体
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static DirectoryEntry GetDirectoryObject(string userName, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(_path + _dnPath, userName, password);
            return entry;
        }

        /// <summary>
        /// 根据指定path,用户名和密码获得相应DirectoryEntry实体
        /// </summary>
        /// <param name="path">完整Path</param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private static DirectoryEntry GetDirectoryObject(string path, string userName, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(path, userName, password);
            return entry;
        }

        #endregion

        #region GetDirectoryEntry

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">ad操作的路径</param>
        /// <param name="ouPath">标识是否是OU路径</param>
        /// <param name="fullPath">true:路径为完整路径,false:ldap路径</param>
        /// <returns></returns>
        public static DirectoryEntry GetDirectoryEntry(string path, bool ouPath, bool fullPath = true)
        {
            try
            {
                if (fullPath)
                {
                    DirectoryEntry entry = GetDirectoryObject(path);
                    entry.Children.Add("OU=User", "organizationalUnit");
                    return entry;
                }
                else
                {
                    DirectoryEntry entry = GetDirectoryObject(_path + path + "," + _dnPath);
                    entry.Children.Add("OU=User", "organizationalUnit");
                    return entry;
                }

            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 根据AccountName取得用户的对象(管理员用户登录)
        /// </summary>
        /// <param name="accountName"></param>
        /// <returns>如果找到该用户,则返回用户的对象,否则返回null</returns>
        public static DirectoryEntry GetDirectoryEntry(string accountName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectCategory=user)(sAMAccountName=" + accountName + "))";
            deSearch.SearchScope = SearchScope.Subtree;

            try
            {
                SearchResult result = deSearch.FindOne();
                de = GetDirectoryObject(result.Path);
                return de;
            }
            catch (Exception ex)
            {
                
                return null;
            }
        }

        /// <summary>
        /// 根据AccountName和密码取得用户的对象,主要做登陆时的验证
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="password"></param>
        /// <returns>如果找到该用户,则返回用户的对象,否则返回null</returns>
        public static DirectoryEntry GetDirectoryEntry(string accountName, string password)
        {
            DirectoryEntry de = GetDirectoryObject(accountName, password);
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectCategory=user)(sAMAccountName=" + accountName + "))";
            deSearch.SearchScope = SearchScope.Subtree;

            try
            {
                SearchResult result = deSearch.FindOne();
                de = GetDirectoryObject(result.Path);
                return de;
            }
            catch (Exception ex)
            {
                
                return null;
            }
        }

        /// <summary>
        /// 根据组名取得用户组的对象(管理员用户登陆)
        /// </summary>
        /// <param name="path">完整path</param>
        /// <param name="groupName"></param>
        /// <returns>返回结果的对象 or Null</returns>
        public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
            deSearch.SearchScope = SearchScope.Subtree;

            try
            {
                SearchResult result = deSearch.FindOne();
                de = GetDirectoryObject(result.Path);
                return de;
            }
            catch (Exception ex)
            {
                
                return null;
            }
        }

        public static DirectoryEntry GetDirectoryEntryOfGroup(string path,string groupName)
        {
            DirectoryEntry de = GetDirectoryObject(path);
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
            deSearch.SearchScope = SearchScope.Subtree;

            try
            {
                SearchResult result = deSearch.FindOne();
                de = GetDirectoryObject(result.Path);
                return de;
            }
            catch (Exception ex)
            {
                
                return null;
            }
        }

        #endregion

        #region CreateUser

        /// <summary>
        /// 创建新用户
        /// </summary>
        /// <param name="ldapDN">去除前段IP,后端DN的部分,由用户信息拼装的OU(不包括User层OU)</param>
        /// <param name="commonName">通用名(displayName,系统中显示的中文字)</param>
        /// <param name="sAMAccountName">Gid,AccountName</param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)
        {
            try
            {
                //首先判断当前Path是否存在,不存在的话再轮询判断生成
                var state = JudgeOrganizeUnit(ldapDN);
                if (state)
                {
                    string userPath = "OU=User," + ldapDN + ",";
                    #region 新需求 如果是服务账号,将放到service account名下
                    if (sAMAccountName.Substring(0, 1).ToLower().Equals("s"))
                    {
                        userPath = "OU=Service Accounts," + ldapDN + ",";
                    }
                    #endregion
                    DirectoryEntry entry = GetDirectoryObject(_path + userPath + _dnPath, AdminName, AdminPwd);
                    //DirectoryEntry subEntry = entry.Children.Find("OU=" + ldapDN, "organizationalUnit");
                    DirectoryEntry deUser = entry.Children.Add("CN=" + commonName.Replace(",", @"\,"), "user");
                    deUser.Properties["sAMAccountName"].Value = sAMAccountName;
                    deUser.CommitChanges();
                    ADHelper.SetProperty(sAMAccountName, "displayname", commonName);
                    ADHelper.SetPassword(sAMAccountName, password);
                    ADHelper.EnableUser(sAMAccountName);

                    //deUser.Dispose();
                    deUser.Close();
                    entry.Dispose();
                    entry.Close();
                    return deUser;
                }
                return null;
            }
            catch (Exception ex)
            {
                
                return null;
            }
        }

        /// <summary>
        /// 设置指定的 属性值
        /// </summary>
        /// <param name="de"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyValue"></param>
        public static void SetProperty(string accountName, string propertyName, string propertyValue)
        {
            DirectoryEntry de = GetDirectoryEntry(accountName);
            if (de == null)
            {
                return;
            }
            if (!string.IsNullOrWhiteSpace(propertyValue))
            {
                if (de.Properties.Contains(propertyName))
                {
                    de.Properties[propertyName][0] = propertyValue;
                }
                else
                {
                    de.Properties[propertyName].Add(propertyValue);
                }
                de.CommitChanges();
            }
            de.Dispose();
            de.Close();
        }

        public static void SetPwdNotExpires(string accountName)
        {
            DirectoryEntry de = GetDirectoryEntry(accountName);
            if (de == null)
            {
                return;
            }
            int userAccountControl_PasswordNeverExpire = Convert.ToInt32(DONT_EXPIRE_PASSWORD);
            int flag = Convert.ToInt32(de.Properties["userAccountControl"][0]) | userAccountControl_PasswordNeverExpire;

            de.Properties["userAccountControl"][0] = flag;

            de.CommitChanges();
            de.Dispose();
            de.Close();
        }

        /// <summary>
        /// 设置用户密码,管理员可以通过它来修改指定用户的密码。
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="newPassword"></param>
        public static void SetPassword(string accountName, string newPassword)
        {
            DirectoryEntry de = GetDirectoryEntry(accountName);

            // 模拟超级管理员,以达到有权限修改用户密码
            //coding here...
            de.Invoke("SetPassword", newPassword);
            #region 新需求
            de.Properties["pwdLastSet"].Value = 0;
            #endregion
            de.CommitChanges();
            de.Dispose();
            de.Close();

        }
        #endregion

        #region organizeUnitOperate

        /// <summary>
        /// 创建OU
        /// </summary>
        /// <param name="OrganizeUnit"></param>
        /// <param name="parentOrganizeUnit"></param>
        /// <returns></returns>
        public static DirectoryEntry CreateOrganizeUnit(string path, string OrganizeUnit)
        {
            DirectoryEntry parentEntry = null;
            try
            {
                parentEntry = GetDirectoryObject(path, AdminName, AdminPwd);
                DirectoryEntry organizeEntry = parentEntry.Children.Add("OU=" + OrganizeUnit, "organizationalUnit");

                organizeEntry.CommitChanges();
                organizeEntry.Dispose();
                organizeEntry.Close();
                return organizeEntry;
            }
            catch (DirectoryServicesCOMException ex)
            {
                
                return null;
            }
            finally
            {
                if (parentEntry != null)
                {
                    parentEntry.Dispose();
                    parentEntry.Close();
                }
            }
        }

        public static bool JudgeOrganizeUnit(string ldapDN)
        {
            //处理需要的Path
            var fullPath = _path + ldapDN + "," + _dnPath;
            var ouLists = ldapDN.Split(',');
            var city = ouLists[0].Split('=').Last();//获取city
            var region = ouLists[2] + "," + ouLists[3] + ",";//获取region
            //开始判断
            DirectoryEntry de = GetDirectoryEntry(fullPath, true);
            try
            {
                if (de == null)
                {

                    string ou = string.Empty;
                    string ouOld = _path + _dnPath;
                    for (int i = ouLists.Length - 1; i >= 0; i--)
                    {
                        ou = ouLists[i] + "," + ou;
                        DirectoryEntry child = GetDirectoryEntry(ouOld, true);
                        if (child != null)
                        {
                            DirectoryEntry tree = GetDirectoryEntry(_path + ou + _dnPath, true);

                            if (tree != null)
                            {
                                ouOld = _path + ou + _dnPath;

                                tree.Dispose();
                                tree.Close();
                                continue;
                            }
                            CreateOrganizeUnit(ouOld, ouLists[i].Substring(3));
                            ouOld = _path + ou + _dnPath;
                        }
                    }
                    //CreateOrganizeUnit(ouOld, "User");
                    //CreateOrganizeUnit(ouOld, "AdminGroup");
                    //CreateOrganizeUnit(_path + region + _dnPath, "AdminGroup");
                }
                CreateOrganizeUnit(fullPath, "User");
                CreateOrganizeUnit(fullPath, "AdminGroup");
                CreateOrganizeUnit(fullPath, "Server");
                CreateOrganizeUnit(fullPath, "Computer");

                #region 新需求
                CreateOrganizeUnit(fullPath, "Production");
                CreateOrganizeUnit(fullPath, "Service Accounts");
                #endregion

                CreateOrganizeUnit(_path + region + _dnPath, "AdminGroup");
                return true;
            }
            catch (Exception ex)
            {
                
                return false;
            }
            finally
            {
                if (de != null)
                {
                    de.Dispose();
                    de.Close();
                }
            }
        }

        /// <summary>
        /// 删除OU
        /// </summary>
        /// <param name="path">要删除的OU的父节点的完整Path</param>
        /// <param name="OrganizeUnit">要删除的OU节点名</param>
        /// <returns>删除成功,return true,else false</returns>
        public static bool DeleteOrganizeUnit(string path, string OrganizeUnit)
        {
            DirectoryEntry parentEntry = null;
            try
            {
                //示例顶级""
                parentEntry = GetDirectoryObject(path, AdminName, AdminPwd);
                DirectoryEntry organizeEntry = parentEntry.Children.Find("OU=" + OrganizeUnit, "organizationalUnit");
                //先删除组织单元下的用户或者组
                parentEntry.Children.Remove(organizeEntry);

                organizeEntry.CommitChanges();
                organizeEntry.Dispose();
                organizeEntry.Close();
                return true;
            }
            catch (DirectoryServicesCOMException ex)
            {
                
                return false;
            }
            finally
            {
                if (parentEntry != null)
                {
                    parentEntry.Dispose();
                    parentEntry.Close();
                }
            }
        }

        #endregion

        #region AccountControl

        /// <summary>
        /// 判断指定名称的用户是否存在,如果存在,返回 true,否则返回 false
        /// </summary>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public static bool IsUserExists(string accountName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectCategory=user)(sAMAccountName=" + accountName + "))";       // LDAP 查询串
            SearchResultCollection results = deSearch.FindAll();

            de.Dispose();
            de.Close();

            if (results.Count == 0)
                return false;
            else
                return true;
        }

        /// <summary>
        /// 判断用户帐号是否激活,如果用户帐号已经激活,返回 true,否则返回 false
        /// </summary>
        /// <param name="userAccountControl"></param>
        /// <returns></returns>
        public static bool IsAccountActive(string accountName)
        {
            if (IsUserExists(accountName))
            {
                DirectoryEntry de = GetDirectoryEntry(accountName);
                int userAccountControl_Disabled = Convert.ToInt32(ACCOUNTDISABLE);
                int flagExists = Convert.ToInt32(de.Properties["userAccountControl"][0]) & userAccountControl_Disabled;

                de.Dispose();
                de.Close();

                if (flagExists > 0)
                    return false;
                else
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 判断账号密码是否永不过期
        /// </summary>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public static bool IsPasswordNotExpires(string accountName)
        {
            if (IsUserExists(accountName))
            {
                DirectoryEntry de = GetDirectoryEntry(accountName);
                if (de == null)
                    return false;
                int userAccountControl_PasswordNeverExpire = Convert.ToInt32(DONT_EXPIRE_PASSWORD);
                int flag = Convert.ToInt32(de.Properties["userAccountControl"][0]) & userAccountControl_PasswordNeverExpire;

                de.Dispose();
                de.Close();

                if (flag > 0)
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 启用指定AD账户
        /// </summary>
        /// <param name="accountName"></param>
        public static void EnableUser(string accountName)
        {
            EnableUser(GetDirectoryEntry(accountName));
        }

        /// <summary>
        /// 启用指定 的用户
        /// </summary>
        /// <param name="de"></param>
        public static void EnableUser(DirectoryEntry de)
        {
            de.Properties["userAccountControl"][0] = NORMAL_ACCOUNT;

            de.CommitChanges();
            de.Dispose();
            de.Close();
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        public static void ChangeUserPassword(string accountName, string oldPassword, string newPassword)
        {
            // to-do: 解决密码策略问题
            DirectoryEntry de = GetDirectoryEntry(accountName);
            de.Invoke("ChangePassword", oldPassword, newPassword);

            de.CommitChanges();
            de.Dispose();
            de.Close();
        }

        /// <summary>
        /// 禁用指定名称的用户
        /// </summary>
        /// <param name="accountName"></param>
        public static void DisableUser(string accountName)
        {
            if (IsUserExists(accountName))
            {
                DisableUser(GetDirectoryEntry(accountName));
            }
        }

        /// <summary>
        /// 禁用指定 的用户
        /// </summary>
        /// <param name="de"></param>
        public static void DisableUser(DirectoryEntry de)
        {
            de.Properties["userAccountControl"][0] = Convert.ToInt32(de.Properties["userAccountControl"][0]) | ACCOUNTDISABLE;

            de.CommitChanges();
            de.Dispose();
            de.Close();
        }

        /// <summary>
        /// 删除指定的用户
        /// </summary>
        /// <param name="accountName"></param>
        public static void DeleteUser(string accountName)
        {
            if (IsUserExists(accountName))
            {
                DirectoryEntry de = GetDirectoryEntry(accountName);
                if (de != null)
                {
                    de.DeleteTree();
                    de.CommitChanges();
                }
                de.Dispose();
                de.Close();
            }
        }

        #endregion

        #region groupOperate

        /// <summary>
        /// 创建group
        /// </summary>
        /// <param name="ldapDN">创建group的Path(不包括CN和IP部分)</param>
        /// <param name="groupName">要创建的group name</param>
        /// <returns></returns>
        public static bool CreateGroup(string ldapDN, string groupName)
        {
            DirectoryEntry parentEntry = null;
            string fullPath = _path + ldapDN + "," + _dnPath;
            try
            {
                if (GetDirectoryEntryOfGroup(fullPath,groupName) != null)
                {
                    return true;
                }
                parentEntry = GetDirectoryObject(fullPath, AdminName, AdminPwd);

                DirectoryEntry groupEntry = parentEntry.Children.Add("CN=" + groupName, "group");

                groupEntry.CommitChanges();
                groupEntry.Dispose();
                groupEntry.Close();
                return true;
            }
            catch (DirectoryServicesCOMException ex)
            {
                
                return false;
            }
            finally
            {
                if (parentEntry != null)
                {
                    parentEntry.Dispose();
                    parentEntry.Close();
                }
            }
        }

        /// <summary>
        /// 创建group 邮件组
        /// </summary>
        /// <param name="ldapDN">创建group的Path(不包括CN和IP部分)</param>
        /// <param name="groupName">group name</param>
        /// <returns></returns>
        public static bool CreateGroup_Universal(string ldapDN, string groupName)
        {
            DirectoryEntry parentEntry = null;
            DirectoryEntry groupEntry = null;
            string fullPath = _path + ldapDN + "," + _dnPath;
            try
            {
                if (GetDirectoryEntryOfGroup(fullPath,groupName) != null)
                {
                    return true;
                }
                parentEntry = GetDirectoryObject(fullPath, AdminName, AdminPwd);

                groupEntry = parentEntry.Children.Add("CN=" + groupName, "group");

                groupEntry.CommitChanges();

                return true;
            }
            catch (DirectoryServicesCOMException ex)
            {
                
                return false;
            }
            finally
            {
                if (groupEntry != null)
                {
                    groupEntry.Properties["groupType"].Value = GROUP_TYPE;
                    groupEntry.CommitChanges();
                    groupEntry.Dispose();
                    groupEntry.Close();
                }
                if (parentEntry != null)
                {

                    parentEntry.Dispose();
                    parentEntry.Close();
                }
            }
        }

        /// <summary>
        /// 删除group
        /// </summary>
        /// <param name="path">要删除的group的Path(不包括CN部分)</param>
        /// <param name="groupName">要删除的group name</param>
        /// <returns></returns>
        public bool DeleteGroup(string path, string groupName)
        {
            DirectoryEntry parentEntry = null;
            try
            {
                parentEntry = GetDirectoryObject(path, AdminName, AdminPwd);
                DirectoryEntry groupEntry = parentEntry.Children.Find("CN=" + groupName, "group");
                parentEntry.Children.Remove(groupEntry);

                groupEntry.CommitChanges();
                groupEntry.Dispose();
                groupEntry.Close();
                return true;
            }
            catch (DirectoryServicesCOMException ex)
            {
                
                return false;
            }
            finally
            {
                if (parentEntry != null)
                {
                    parentEntry.Dispose();
                    parentEntry.Close();
                }
            }
        }

        /// <summary>
        /// 将指定的用户添加到指定的组中
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="groupName"></param>
        public static bool AddUserToGroup(string path, string accountName, string groupName)
        {
            string fullPath = _path + path + "," + _dnPath;
            try
            {
                DirectoryEntry oGroup = GetDirectoryEntryOfGroup(fullPath,groupName);
                if (oGroup == null)
                {
                    //CreateGroup(groupPath, groupName);
                    //oGroup = GetDirectoryEntryOfGroup(_path + groupPath + _dnPath, groupName);
                    return false;
                }
                DirectoryEntry oUser = GetDirectoryEntry(accountName);

                oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);

                oGroup.CommitChanges();
                oGroup.Dispose();
                oGroup.Close();
                oUser.Dispose();
                oUser.Close();
                return true;
            }
            catch (Exception ex)
            {
                
                return false;
            }
        }

        /// <summary>
        /// 将用户从指定组中移除。默认为 Users 下的组和用户。
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="groupName"></param>
        public static void RemoveUserFromGroup(string path, string accountName, string groupName)
        {
            string fullPath = _path + path ;
            if (!fullPath.Contains(_dnPath))
                fullPath = fullPath+ "," + _dnPath;

            DirectoryEntry oGroup = GetDirectoryEntryOfGroup(fullPath,groupName);
            DirectoryEntry oUser = GetDirectoryEntry(accountName);

            oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);

            oGroup.CommitChanges();
            oGroup.Dispose();
            oGroup.Close();
            oUser.Dispose();
            oUser.Close();
        }

        public static void RemoveUserFromGroup(string accountName, string groupName)
        {
           
            DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
            DirectoryEntry oUser = GetDirectoryEntry(accountName);

            oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);

            oGroup.CommitChanges();
            oGroup.Dispose();
            oGroup.Close();
            oUser.Dispose();
            oUser.Close();
        }


        /// <summary>
        /// 将用户移除出组,传入AdAccount,查询memberof属性获取所属组。
        /// </summary>
        /// <param name="accountName"></param>
        public static void RemoveUserFromGroup(string accountName)
        {
            DirectoryEntry oUser = GetDirectoryEntry(accountName);

            var objs = oUser.Properties["memberof"];
            foreach (var item in objs)
            {
                string prefix = (item.ToString().Split(',').First()).Split('=').Last(); ;
                ADHelper.RemoveUserFromGroup(item.ToString(), accountName, prefix);
            }
        }

        public static string GetAccountPath(string accountName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectCategory=user)(sAMAccountName=" + accountName + "))";       // LDAP 查询串
            deSearch.PropertiesToLoad.Add("DistinguishedName");
            deSearch.SearchScope = SearchScope.Subtree;
            SearchResultCollection results = deSearch.FindAll();
            SearchResult managerResult;
            string managerName = "";
            if (results != null)
            {
                managerResult = results[0];
                managerName =
                  (string)managerResult.Properties["DistinguishedName"][0];
            }

            de.Dispose();
            de.Close();

            return managerName;
        }

        public static void SetAccountExpires(string accountName, string accountExpires)
        {
            if (!string.IsNullOrEmpty(accountExpires))
            {
                DirectoryEntry de = GetDirectoryEntry(accountName);
                if (accountExpires != "0")
                {
                   

                    DateTime expiresDate = Convert.ToDateTime(accountExpires);
                    expiresDate = expiresDate.AddDays(2);


                    de.InvokeSet(
                    "AccountExpirationDate",
                    new object[] { expiresDate });
                            de.CommitChanges();
                            de.Dispose();
                            de.Close();
                }
                else
                {
                    de.InvokeSet(
                   "AccountExpires",
                   0);
                    de.CommitChanges();
                    de.Dispose();
                    de.Close();
                }
            }
        }
        #endregion
    }

    public class ADUser
    {
        public string AdAccount { get; set; }

        public string Email { get; set; }

        public string DisplayName { get; set; }

        public DateTime LastLogonTime { get; set; }

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值