在云那方

首页 新随笔 联系 订阅 管理

创建邮箱参考:http://sunjiangwei.iteye.com/blog/1590408

using System.DirectoryServices (C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll)

using System.Management.Automation (C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll)

MailBoxHelper.cs

View Code
    /// <summary>
    /// 创建AD邮箱会自动创建AD帐号
    /// <add key="MailDB" value="MDB-01"/>
    /// <add key="OU"  value="OU=New,OU=Users,OU=XXX,DC=XXX,DC=loc"/>
    /// </summary>
    public class MailBoxHelper
    {
        /// <summary>
        /// Domain
        /// </summary>
        private static string Domain = ConfigurationManager.AppSettings["Domain"];

        /// <summary>
        /// 邮箱
        /// </summary>
        private static string MailDB = ConfigurationManager.AppSettings["MailDB"];

        /// <summary>
        /// 组织架构
        /// </summary>
        private static string OU = ConfigurationManager.AppSettings["OU"];

        /// <summary>
        /// 邮箱是否存在
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static bool IsExistMailBox(string userName)
        {
            try
            {
                var parms = new Hashtable();
                parms.Add("identity", userName + Domain);
                var result = ExceCommand("Get-Mailbox", parms);
                return (result != null && result.Count > 0);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 创建邮箱和账号
        /// </summary>
        /// <param name="adUser"></param>
        /// <returns></returns>
        public static bool CreateMailbox(ADUser adUser)
        {
            if (string.IsNullOrEmpty(adUser.UserName)) throw new ArgumentNullException("用户名");
            if (string.IsNullOrEmpty(adUser.Password)) throw new ArgumentNullException("密码");



            string email = adUser.UserName + Domain;

            if (IsExistMailBox(email)) throw new Exception("邮箱已存在");
            try
            {
                var parms = new Hashtable();
                
                parms.Add("UserPrincipalName", email);//邮箱地址
                parms.Add("SamAccountName", adUser.UserName);//登录名

                if (!string.IsNullOrEmpty(adUser.Name))
                {
                    parms.Add("Name", adUser.Name); //姓名
                }

                char[] chArray = adUser.Password.ToCharArray();
                SecureString str = new SecureString();
                foreach (char ch in chArray)
                {
                    str.AppendChar(ch);
                }
                parms.Add("Password", str);//密码


                parms.Add("OrganizationalUnit", OU);//组织单元
                parms.Add("DataBase", MailDB);//数据库

                ExceCommand("New-Mailbox", parms);

                Log.SuccessLog(string.Format("创建帐号{0}成功", adUser.UserName));

                return true;
            }
            catch (Exception ex)
            {
                Log.ErrorLog(string.Format("创建帐号{0}失败,{1}", adUser.UserName, ex.ToString()));
            }
            return false;
        }

        /// <summary>
        /// 删除邮箱账号(控制台和域都删除)
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static bool RemoveMailbox(string userName)
        {
            try
            {
                var parms = new Hashtable();
                parms.Add("identity", userName + Domain);
                parms.Add("Confirm", false);

                ExceCommand("Remove-Mailbox", parms);

                Log.SuccessLog(string.Format("删除帐号{0}成功", userName));

                return true;
            }
            catch (Exception ex)
            {
                Log.ErrorLog(string.Format("删除帐号{0}失败,{1}", userName, ex.ToString()));
            }
            return false;
        }

        /// <summary>
        /// 启用邮箱账号
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static bool EnableMailbox(string userName)
        {
            try
            {
                var parms = new Hashtable();
                parms.Add("identity", userName + Domain);
                parms.Add("Confirm", false);

                ExceCommand("Enable-Mailbox", parms);

                Log.SuccessLog(string.Format("启用帐号{0}成功", userName));

                return true;
            }
            catch (Exception ex)
            {
                Log.ErrorLog(string.Format("启用帐号{0}失败,{1}", userName, ex.ToString()));
            }
            return false;
        }

        /// <summary>
        /// 禁用邮箱账号
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        public static bool DisableMailbox(string userName)
        {
            try
            {
                var parms = new Hashtable();
                parms.Add("identity", userName + Domain);
                parms.Add("Confirm", false);

                ExceCommand("Disable-Mailbox", parms);

                Log.SuccessLog(string.Format("禁用帐号{0}成功", userName));

                return true;
            }
            catch (Exception ex)
            {
                Log.ErrorLog(string.Format("禁用帐号{0}失败,{1}", userName, ex.ToString()));
            }
            return false;
        }

        /// <summary>
        /// 执行Powershell命令
        /// </summary>
        /// <param name="commandName"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        private static Collection<PSObject> ExceCommand(string commandName, Hashtable parms)
        {
            PSSnapInException PSException = null;
            RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
            runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            Command command = new Command(commandName);

            foreach (DictionaryEntry entry in parms)
            {
                command.Parameters.Add(entry.Key.ToString(), entry.Value);
            }

            pipeline.Commands.Add(command);
            Collection<PSObject> result = pipeline.Invoke();

            string message = string.Empty;
            if ((pipeline.Error != null) && (pipeline.Error.Count > 0))
            {
                foreach (object obj2 in pipeline.Error.ReadToEnd())
                {
                    message = message + obj2.ToString() + "|";
                }
                throw new Exception(message);
            }
            runspace.Close();
            return result;
        }
    }

 

ADHelper.cs

View Code
public class ADHelper
    {
        /// <summary>
        
/// 域名
        
/// </summary>
        private static string ADPath = ConfigurationManager.AppSettings["ADPath"];

        /// <summary>
        
/// 管理员
        
/// </summary>
        private static string ADUser = ConfigurationManager.AppSettings["ADUser"];

        /// <summary>
        
/// 管理密码
        
/// </summary>
        private static string ADPassword = ConfigurationManager.AppSettings["ADPassword"];

        /// <summary>
        
/// 获取AD操作对象
        
/// </summary>
        
/// <returns></returns>
        private static DirectoryEntry GetDirectoryEntry()
        {
            return new DirectoryEntry(string.Format("LDAP://{0}", ADPath), ADUser, ADPassword, AuthenticationTypes.ServerBind);
        }

        /// <summary>
        
/// 用户是否存在
        
/// </summary>
        
/// <param name="userName">用户名</param>
        
/// <returns></returns>
        public static bool UserIsExist(string userName)
        {
            var deUser = GetUserByName(userName);
            return deUser != null ? true : false;
        }

        /// <summary>
        
/// 获取用户
        
/// </summary>
        
/// <param name="userName">用户名</param>
        
/// <returns></returns>
        public static DirectoryEntry GetUserByName(string userName)
        {
            var de = GetDirectoryEntry();
            try
            {
                if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("用户名");

                DirectorySearcher deSearch = new DirectorySearcher();
                deSearch.SearchRoot = de;
                deSearch.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", userName);
                var result = deSearch.FindOne();
                if (result != null)
                {
                    return result.GetDirectoryEntry();
                }

                return null;
            }
            catch (Exception ex)
            {
                throw new Exception("获取用户失败", ex);
            }
            finally
            {
                de.Dispose();
            }
        }

        /// <summary>
        
/// 添加帐户
        
/// </summary>
        
/// <param name="adUser">用户类</param>
        
/// <returns></returns>
        public static bool AddUser(ADUser adUser)
        {
            if (string.IsNullOrEmpty(adUser.UserName)) throw new ArgumentNullException("用户名");
            if (string.IsNullOrEmpty(adUser.Password)) throw new ArgumentNullException("密码");

            var de = GetDirectoryEntry();
            var deUser = de.Children.Add(string.Format("CN={0},CN=users", adUser.UserName), "user");
            try
            {
                deUser.Properties["sAMAccountName"].Value = adUser.UserName;   //win2000以前登录名
                deUser.Properties["userPrincipalName"].Value = string.Format("{0}@{1}", adUser.UserName, ADPath);  //用户登录名

                
//deUser.Properties["GivenName"].Value = "44";
                
//deUser.Properties["sn"].Value = "55";
                
//deUser.Properties["displayName"].Value = "11";
                
//deUser.Properties["Name"].Value = "22";

                if (!string.IsNullOrEmpty(adUser.Name))
                {
                    deUser.Properties["displayName"].Value = adUser.Name;      //显示姓名
                }
                if (!string.IsNullOrEmpty(adUser.Description))
                {
                    deUser.Properties["description"].Value = adUser.Description;  //备注
                }
                deUser.CommitChanges();

                //设置密码
                ChangePassword(adUser.UserName, "", adUser.Password);
                //启用帐户
                EnableUser(adUser.UserName);

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("添加用户失败", ex);
            }
            finally
            {
                deUser.Dispose();
                de.Dispose();
            }

        }

        /// <summary>
        
/// 修改用户
        
/// </summary>
        
/// <param name="userName">用户名</param>
        
/// <returns></returns>
        public static bool UpdateUser(ADUser adUser)
        {
            var deUser = GetUserByName(adUser.UserName);
            if (deUser == nullthrow new Exception("用户不存在");

            try
            {
                if (!string.IsNullOrEmpty(adUser.Name))
                {
                    deUser.Properties["Name"].Value = adUser.Name;      //显示姓名
                }
                if (!string.IsNullOrEmpty(adUser.Description))
                {
                    deUser.Properties["description"].Value = adUser.Description;  //备注
                }
                deUser.CommitChanges();

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("修改用户失败", ex);
            }
            finally
            {
                deUser.Dispose();
            }
        }

        /// <summary>
        
/// 删除用户
        
/// </summary>
        
/// <param name="userName">用户名</param>
        
/// <returns></returns>
        public static bool DeleteUser(string userName)
        {
            var deUser = GetUserByName(userName);
            if (deUser == nullthrow new Exception("用户不存在");

            try
            {
                deUser.DeleteTree();
                deUser.CommitChanges();

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("删除用户失败", ex);
            }
            finally
            {
                deUser.Dispose();
            }
        }

        /// <summary>
        
/// 启用帐户
        
/// </summary>
        
/// <param name="userName"></param>
        public static bool EnableUser(string userName)
        {
            var deUser = GetUserByName(userName);
            if (deUser == nullthrow new Exception("用户不存在");
            try
            {
                deUser.Properties["userAccountControl"][0] = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
                deUser.CommitChanges();
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("启用用户失败", ex);
            }
            finally
            {
                deUser.Dispose();
            }
        }

        /// <summary>
        
/// 禁用帐户
        
/// </summary>
        
/// <param name="userName"></param>
        public static bool DisableUser(string userName)
        {
            var deUser = GetUserByName(userName);
            if (deUser == nullthrow new Exception("用户不存在");
            try
            {
                deUser.Properties["userAccountControl"][0] = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
                deUser.CommitChanges();
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("禁用用户失败", ex);
            }
            finally
            {
                deUser.Dispose();
            }
        }

        /// <summary>
        
/// 修改密码
        
/// </summary>
        
/// <param name="userName"></param>
        
/// <param name="oldPassword"></param>
        
/// <param name="password"></param>
        public static bool ChangePassword(string userName, string oldPassword, string password)
        {
            var deUser = GetUserByName(userName);
            if (deUser == nullthrow new Exception("用户不存在");
            try
            {
                deUser.Invoke("ChangePassword"new object[] { oldPassword, password });
                deUser.CommitChanges();
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("修改密码失败", ex);
            }
            finally
            {
                deUser.Dispose();
            }
        }

        #region 用户属性定义标志
        /// <summary>
        
/// 用户属性定义标志
        
/// </summary>
        public enum ADS_USER_FLAG_ENUM
        {
            /// <summary>
            
/// 登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。
            
/// </summary>
            ADS_UF_SCRIPT = 0X0001,
            /// <summary>
            
/// 用户帐号禁用标志
            
/// </summary>
            ADS_UF_ACCOUNTDISABLE = 0X0002,
            /// <summary>
            
/// 主文件夹标志
            
/// </summary>
            ADS_UF_HOMEDIR_REQUIRED = 0X0008,
            /// <summary>
            
/// 过期标志
            
/// </summary>
            ADS_UF_LOCKOUT = 0X0010,
            /// <summary>
            
/// 用户密码不是必须的
            
/// </summary>
            ADS_UF_PASSWD_NOTREQD = 0X0020,
            /// <summary>
            
/// 密码不能更改标志
            
/// </summary>
            ADS_UF_PASSWD_CANT_CHANGE = 0X0040,
            /// <summary>
            
/// 使用可逆的加密保存密码
            
/// </summary>
            ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
            /// <summary>
            
/// 本地帐号标志
            
/// </summary>
            ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,
            /// <summary>
            
/// 普通用户的默认帐号类型
            
/// </summary>
            ADS_UF_NORMAL_ACCOUNT = 0X0200,
            /// <summary>
            
/// 跨域的信任帐号标志
            
/// </summary>
            ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,
            /// <summary>
            
/// 工作站信任帐号标志
            
/// </summary>
            ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
            /// <summary>
            
/// 服务器信任帐号标志
            
/// </summary>
            ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,
            /// <summary>
            
/// 密码永不过期标志
            
/// </summary>
            ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,
            /// <summary>
            
/// MNS 帐号标志
            
/// </summary>
            ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
            /// <summary>
            
/// 交互式登录必须使用智能卡
            
/// </summary>
            ADS_UF_SMARTCARD_REQUIRED = 0X40000,
            /// <summary>
            
/// 当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任
            
/// </summary>
            ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
            /// <summary>
            
/// 当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托
            
/// </summary>
            ADS_UF_NOT_DELEGATED = 0X100000,
            /// <summary>
            
/// 此帐号需要 DES 加密类型
            
/// </summary>
            ADS_UF_USE_DES_KEY_ONLY = 0X200000,
            /// <summary>
            
/// 不要进行 Kerberos 预身份验证
            
/// </summary>
            ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
            /// <summary>
            
/// 用户密码过期标志
            
/// </summary>
            ADS_UF_PASSWORD_EXPIRED = 0X800000,
            /// <summary>
            
/// 用户帐号可委托标志
            
/// </summary>
            ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
        }
        #endregion
    }

 

ADUser.cs

 

View Code
public class ADUser
    {
        /// <summary>
        
/// 用户名
        
/// </summary>
        public string UserName { getset; }

        /// <summary>
        
/// 密码
        
/// </summary>
        public string Password { getset; }

        /// <summary>
        
/// 姓名
        
/// </summary>
        public string Name { getset; }

        /// <summary>
        
/// 备注
        
/// </summary>
        public string Description { getset; }
    }

 

posted on 2012-11-27 12:08  Rich.T  阅读(790)  评论(0编辑  收藏  举报