C# 操作AD域,新建用户、组织、组

     前一段时间做了一个从SHR系统 同步用户、组织的小程序,现在分享给大家;

 废话不多说,直接上代码。

     首先引用:using System.DirectoryServices;

    定义基本连接属性:

  private string RootPath = "OU=TestOU,DC=ittest,DC=com"; //根路径
  private string ADPath = "LDAP://10.10.9.230/" ; //主机地址
  private string ADUser = "sunlizhen"; //登录账户
        //AD管理员密码
  private  string ADPasssWord = "abc123";//密码

  获取DirectoryEntry 对象

 private  DirectoryEntry GetDirectoryObject(string path ="")
        {
             //path LDAP://10.10.9.230/OU=TestOU,DC=ittest,DC=com
            DirectoryEntry entry = null;
            try
            { if (path == "")
                {
                    entry = new DirectoryEntry(ADPath + RootPath, ADUser, ADPasssWord, AuthenticationTypes.Secure);
                }
                else
                {
                    entry = new DirectoryEntry(path, ADUser, ADPasssWord, AuthenticationTypes.Secure);
                    string newguid = entry.Guid.ToString();

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

获取用户对象

/// <summary>
        /// 根据用户公共名称取得用户的 对象
        /// </summary>
        /// <param name="commonName">用户公共名称</param>
        /// <returns>如果找到该用户则返回用户的对象,否则返回 null</returns>
        public  DirectoryEntry GetUserEntry(string commonName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName.Replace("\\", "") + "))";
            deSearch.SearchScope = SearchScope.Subtree;
            try
            {
                SearchResult result = deSearch.FindOne();
                if (result == null)
                    return null;
                //de = new DirectoryEntry(result.Path);
                de = GetDirectoryObject(result.Path);
                return de;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

获取组织对象

/// <summary>
        // 获取组织单位
        /// </summary>
     
        /// <param name="ouname">组织名称</param>
        /// <returns></returns>
        public DirectoryEntry GetOU(string ouname)
        {
           
            DirectorySearcher deSearch = new DirectorySearcher();
            deSearch.Filter = string.Format("(&(objectClass=organizationalUnit) (OU={0}))", ouname);
            SearchResult results = deSearch.FindOne();
            if (results != null)
            {
                return results.GetDirectoryEntry();
            }
            else
            {
                return null;
            }
        }

获取group对象

/// <summary>
        /// 根据组名获取组织对象
        /// </summary>
        /// <param name="commonName">组名</param>
        /// <returns>如果找到该用户则返回用户的对象,否则返回 null</returns>
        public DirectoryEntry GetGroupEntry(string commonName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectClass=group)(cn=" + commonName + "))";
            deSearch.SearchScope = SearchScope.Subtree;
            try
            {
                SearchResult result = deSearch.FindOne();
                if (result == null)
                    return null;
                //  de = new DirectoryEntry(result.Path);
                de = GetDirectoryObject(result.Path);
                return de;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

获取用户列表

/// <summary>
        /// 获取用户信息转换成Datatable
        /// </summary>
        public  void GetUserList()
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(objectClass=user)";

            //deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName.Replace("\\", "") + "))";

            SearchResultCollection searchResultCollection = deSearch.FindAll();
            string[] DirectoryList = new string[searchResultCollection.Count];
            //string[] Columns = config.AppSettings.Settings["UserColumn"].Value.Split(",".ToCharArray());
            //deSearch.PropertiesToLoad.AddRange(Columns);
               deSearch.PropertiesToLoad.AddRange(new string[] { "name", "Path"});

            SearchResult sr = deSearch.FindOne();
            UserTable = new DataTable();
            // GroupTable.Columns.Add("CN");
            System.Collections.ICollection propColls = sr.Properties.PropertyNames;
            foreach (object item in propColls)
            {
                // 创建datatable的列
                UserTable.Columns.Add(item.ToString());

            }
            foreach (SearchResult item in searchResultCollection)
            {
                DataRow dr = UserTable.NewRow();
                foreach (object item02 in propColls)
                {  try
                    {
                        dr[item02.ToString()] = item.Properties[item02.ToString()][0].ToString();
                    }
                    catch
                    { 
                    
                    }
                }
                UserTable.Rows.Add(dr);
            }


        }

新建用户 或更新用户信息

     /// <summary>
       /// 
       /// </summary>
       /// <param name="login">用户ID</param>
       /// <param name="pareapath">组织路径</param>
       /// <param name="PropertyVlues">属性结合,可自行查询属性名</param>
public void CreateNewUser(string login, string pareapath, Dictionary<string, string> PropertyVlues)
        {
            //如果用户信息存在,就变为更新

            pareapath = GetFullPathName(pareapath);
            //Catalog catalog = new Catalog();
            DirectoryEntry de = GetOrgEntry(pareapath);
            if (de == null)
            {
                Common.Sys.Record("---warning---");
                Common.Sys.Record(login + " " + pareapath + "找不到对应的组织数据");
                Common.Sys.Record("---warning---");
                // 找不到组织
                return;
            }
            //遍历key 判断账户是否禁用
            bool DisableState = true;
            foreach (string key in PropertyVlues.Keys)
            {
                if (key == "DisableState")
                {
                    if (PropertyVlues[key] == "0")
                    {
                        DisableState = false;
                    }
                    break;
                }              
            }


            /// 1. Create user account
            DirectoryEntries users = de.Children;
            DirectoryEntry newuser = users.Add("CN=" + login, "user");

            DirectoryEntry olduser = GetUserEntry(login);
            if (olduser != null)
            {
                Common.Sys.Record(login + " " + pareapath + "用户信息已经存在,开始更新信息");
                // 找不到组织
                if (DisableState)
                {
                    DisableAccount(olduser);
                    Common.Sys.Record(login +  "账户禁用");
                    return;
                }


                newuser = olduser;
                if (de.Path != olduser.Parent.Path)
                {
                    newuser.MoveTo(de);
                    Common.Sys.Record(login + " 组织由" + olduser.Parent.Path + "变更为" + de.Path);
                }
            }
            else
            {
                if (DisableState)
                {                    
                    Common.Sys.Record(login + "离职,无须新建");
                    return;
                }


                newuser.CommitChanges();
                /// 3. Set password
                newuser.AuthenticationType = AuthenticationTypes.Secure;
                object[] password = new object[] { ADHelper.SetSecurePassword() };
                object ret = newuser.Invoke("SetPassword", password);
                newuser.CommitChanges();
                Common.Sys.Record(login + " " + pareapath + "密码设置成功");

                /// 4. Enable account           
                EnableAccount(newuser);
                Common.Sys.Record(login + " " + pareapath + "账户启用");
            }
            /// 2. Set properties
            //遍历key
            foreach (string key in PropertyVlues.Keys)
            {
                if (key == "DisableState") // 账户禁用跳过
                {
                    continue;
                }
                if (key == "manager")
                {
                    DirectoryEntry manger = GetUserEntry(PropertyVlues[key]);
                    if (manger != null)
                    {
                        newuser.Properties["manager"].Value = manger.Properties["distinguishedName"].Value;
                        newuser.CommitChanges();
                        Common.Sys.Record(login + " " + "管理者更新完毕");
                    }                    
                    continue;
                }
                else
                { 
                  ADHelper.SetProperty(newuser, key, PropertyVlues[key]);
                 }
                newuser.CommitChanges();
            }
            //newuser.CommitChanges();
            Common.Sys.Record(login + " " + "属性更新完毕");
            /// 5. Add user account to groups
            AddUserToGroup(de, newuser, de.Name.Replace("OU=",""));
           
            /// 6. Create a mailbox in Microsoft Exchange   
            //GenerateMailBox(login);

            newuser.Close();
            de.Close();
        }
/// <summary>
        /// 设置指定的属性值
        /// </summary>
        /// <param name="de"></param>
        /// <param name="propertyName">属性名称?</param>
        /// <param name="propertyValue">属性值</param>
        public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
        {
            if (de.Properties.Contains(propertyName))
            {
                if (String.IsNullOrEmpty(propertyValue))
                {
                    de.Properties[propertyName].RemoveAt(0);
                }
                else
                {
                    de.Properties[propertyName][0] = propertyValue;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(propertyValue))
                {
                    de.Properties[propertyName].Add(propertyValue);
                }
            }
        }



        /// <summary>
        /// 生成随机密码
        /// </summary>
        /// <returns></returns>
        public static string SetSecurePassword()
        {
            //RandomPassword rp = new RandomPassword();

          //  config.AppSettings.Settings["UserColumn"].Value.Split(",".ToCharArray());
            return config.AppSettings.Settings["ADPassWord"].Value.ToString();
        }

        /// <summary>
        /// 设置用户新密码
        /// </summary>
        /// <param name="path"></param>
        public static void SetPassword(DirectoryEntry newuser)
        {
            
            newuser.AuthenticationType = AuthenticationTypes.Secure;
            object[] password = new object[] { SetSecurePassword() };
            object ret = newuser.Invoke("SetPassword", password);
            newuser.CommitChanges();
            newuser.Close();

        }
      /// <summary>
            /// 启用用户帐号
            /// </summary>
            /// <param name="de"></param>
         private static void EnableAccount(DirectoryEntry de)
        {
           
            de.Properties["userAccountControl"].Value = 544;
            de.CommitChanges();
        }
        /// <summary>
        /// 禁用用户帐号
        /// </summary>
        /// <param name="de"></param>
        private static void DisableAccount(DirectoryEntry de)
        {
            de.Properties["userAccountControl"].Value = 546;
            de.CommitChanges();

        }
       

添加用户到组

/// <summary>
        /// 添加用户到组
        /// </summary>
        /// <param name="de"></param>
        /// <param name="deUser"></param>
        /// <param name="GroupName"></param>
        public  void AddUserToGroup(DirectoryEntry de, DirectoryEntry deUser, string GroupName)
        {
            DirectorySearcher deSearch = new DirectorySearcher();
            deSearch.SearchRoot = de;
           // deSearch.Filter = "(&(objectClass=group) (cn=" + GroupName + "))";
            deSearch.Filter = "(objectClass=group)";
            SearchResultCollection results = deSearch.FindAll();

            bool isGroupMember = false;
            object userADGroups = deUser.Invoke("groups",null);

            //string[] groups = (string[])deUser.Properties["memberOf"].Value;
            string groupName = "";
            if (results.Count > 0)
            {
                DirectoryEntry group = GetDirectoryObject(results[0].Path.ToString());
                groupName = group.Properties["distinguishedName"][0].ToString();
                //item.Properties["distinguishedName"][0].ToString()
            }


            if (results.Count > 0)
            {
                DirectoryEntry group = GetDirectoryObject(results[0].Path.ToString());

                object members = group.Invoke("Members", null);
                foreach (object member in (IEnumerable)members)
                {
                    DirectoryEntry x = new DirectoryEntry(member);
                    if (x.Name != deUser.Name)
                    {
                        isGroupMember = false;
                    }
                    else
                    {
                        isGroupMember = true;
                        break;
                    }
                }

                if (!isGroupMember)
                {
                    group.Invoke("Add", new object[] { deUser.Path.ToString() });
                    Common.Sys.Record("组"+groupName + "添加用户:" + deUser.Name + "完毕");
                }
                group.Close();
            }
             // 删除用户不同组织下的组
            foreach (string groupDN in deUser.Properties["memberOf"])
            {
                if (groupDN != groupName)
                {
                    DirectoryEntry group = GetDirectoryObject(ADPath + groupDN);
                    group.Invoke("Remove", new object[] { deUser.Path.ToString() });
                    Common.Sys.Record("组" + group.Name + "删除用户:" + deUser.Name + "完毕");
                }               
            }


            return;
        }

添加OU 组织

 /// <summary>
        /// 
        /// </summary>
        /// <param name="ouname">组织名称</param>
        /// <param name="DisplayName">显示名称</param>
        /// <param name="pareapath">父路径</param>

        //  OU=TestOU,DC=ittest,DC=com
        public void AddOU(string ouname,string DisplayName,string pareapath)
        {
            if (pareapath == "")
            {
                pareapath =  RootPath;
            }
            else
            {
                pareapath =  pareapath +","+ RootPath;
            }
            try
            {
                DirectoryEntry pare = GetOrgEntry(pareapath);
                //pare.Rename("OU=" + "MIS004");
                DirectoryEntry newadd = pare.Children.Add("OU=" + ouname, "organizationalUnit");
                // DirectoryEntry newadd = pare.Children.Add("CN=" + ouname, "user");
                // 判断是否存在
                DirectoryEntry oldord = GetDirectoryObject(newadd.Path);
                if (oldord!=null)
                {
                    Common.Sys.Record(ouname +  " "+ DisplayName + " " + pareapath + "组织存在,开始更新");
                    newadd = oldord;
                }

                ADHelper.SetProperty(newadd, "displayName", DisplayName);
                ADHelper.SetProperty(newadd, "description", DisplayName);
                newadd.CommitChanges();
                Common.Sys.Record(ouname + " " + DisplayName + " " + pareapath + "组织更新完毕");
            }
            catch
            {


            }
        }
       /// 删除ou

        public  void ReMoveOU(string ouname)
        {
            DirectoryEntry OUEntry = GetOrgEntry(ouname);
            DirectoryEntry OUParent = OUEntry.Parent;
            OUParent.Children.Remove(OUEntry);
            OUParent.CommitChanges();
        }

        

添加 组

/// <summary>
        /// 
        /// </summary>
        /// <param name="ouname"></param>
        /// <param name="DisplayName"></param>
        /// <param name="pareapath"></param>
        public void AddGroup(string ouname, string DisplayName, string pareapath)
        {
            if (pareapath == "")
            {
                pareapath =  RootPath;
            }
            else
            {
                pareapath =  pareapath + "," + RootPath;
            }
            try
            {
                DirectoryEntry pare = GetOrgEntry(pareapath);
                //pare.Rename("OU=" + "MIS004");
                DirectoryEntry newadd = pare.Children.Add("CN=" + ouname, "group");
                // DirectoryEntry newadd = pare.Children.Add("CN=" + ouname, "user");
                // 判断是否存在
                DirectoryEntry oldord = GetGroupEntry(ouname);
                if (oldord != null)
                {                   

                    if (pare.Path != oldord.Parent.Path)
                    {
                        oldord.MoveTo(pare);                   
                        Common.Sys.Record(ouname + " 组移动");
                    }

                    Common.Sys.Record(ouname + " " + DisplayName +" " +pareapath + "组存在,开始更新");
                    newadd = oldord;
                }
                ADHelper.SetProperty(newadd, "displayName", DisplayName);
                ADHelper.SetProperty(newadd, "description", DisplayName);
                ADHelper.SetProperty(newadd, "sAMAccountName", ouname);                
                ADHelper.SetProperty(newadd, "groupType", "-2147483640");
                
                newadd.CommitChanges();
                Common.Sys.Record(ouname + " " + DisplayName + " " + pareapath  + "组更新完毕");
            }
            catch
            {


            }
        }

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值