关于AD的操作--users 类

本文介绍了一种实现高效AD账户管理的方法,包括用户创建、更新、删除、密码修改及组织结构调整等功能。通过使用统一的类结构和方法调用,简化了AD操作流程,提高了管理效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

namespace TB.ADBlock
{
    using ActiveDs;
    using System;
    using System.Collections.Generic;
    using System.DirectoryServices;


    public class User : BaseObject
    {
        private string department;
        private string displayName;
        private string firstName;
        private string initials;
        private string lastName;
        private string mail;
        private string manager;
        private string[] memberOf;
        private string mobile;
        private string office;
        private int? primaryGroupID;
        private string principalName;
        public const string PROPERTY_ACCOUNT_CONTROL = "userAccountControl";
        public const string PROPERTY_ACCOUNT_EXPIRES = "accountExpires";
        public const string PROPERTY_ACCOUNT_PRINCIPAL = "userPrincipalName";
        public const string PROPERTY_ACCOUNT_PWDLASTSET = "pwdLastSet";
        public const string PROPERTY_ACCOUNT_SAM = "sAMAccountName";
        public const string PROPERTY_ACCOUNT_TYPE = "sAMAccountType";
        public const string PROPERTY_ADDRESS_CITY = "l";
        public const string PROPERTY_ADDRESS_COUNTRY = "co";
        public const string PROPERTY_ADDRESS_COUNTRYAB = "c";
        public const string PROPERTY_ADDRESS_COUNTRYCODE = "countryCode";
        public const string PROPERTY_ADDRESS_POSTALCODE = "postalCode";
        public const string PROPERTY_ADDRESS_POSTBOX = "postOfficeBox";
        public const string PROPERTY_ADDRESS_PROVINCE = "st";
        public const string PROPERTY_ADDRESS_STREET = "streetAddress";
        public const string PROPERTY_BADPASSWORDTIME = "badPasswordTime";
        public const string PROPERTY_BADPWDCOUNT = "badPwdCount";
        public const string PROPERTY_CN = "cn";
        public const string PROPERTY_CODEPAGE = "codePage";
        public const string PROPERTY_GENERAL_DESCRIPTION = "description";
        public const string PROPERTY_GENERAL_DISPLAYNAME = "displayName";
        public const string PROPERTY_GENERAL_GIVENNAME = "givenName";
        public const string PROPERTY_GENERAL_HOMEPAGE = "wWWHomePage";
        public const string PROPERTY_GENERAL_INITIALS = "initials";
        public const string PROPERTY_GENERAL_LASTNAME = "sn";
        public const string PROPERTY_GENERAL_MAIL = "mail";
        public const string PROPERTY_GENERAL_OFFICE = "physicalDeliveryOfficeName";
        public const string PROPERTY_GENERAL_TEL = "telephoneNumber";
        public const string PROPERTY_LASTLOGOFF = "lastLogoff";
        public const string PROPERTY_LASTLOGON = "lastLogon";
        public const string PROPERTY_LOGONCOUNT = "logonCount";
        public const string PROPERTY_MEMBEROF_ALL = "memberOf";
        public const string PROPERTY_MEMBEROF_PRIMARY = "primaryGroupID";
        public const string PROPERTY_ORGAN_COMPANY = "company";
        public const string PROPERTY_ORGAN_DEPARTMENT = "department";
        public const string PROPERTY_ORGAN_MANAGER = "manager";
        public const string PROPERTY_ORGAN_TITLE = "title";
        public const string PROPERTY_ORGAN_UNDERLING = "directReports";
        public const string PROPERTY_TEL_FAX = "facsimileTelephoneNumber";
        public const string PROPERTY_TEL_FAXO = "otherFacsimileTelephoneNumber";
        public const string PROPERTY_TEL_INFO = "info";
        public const string PROPERTY_TEL_IP = "ipPhone";
        public const string PROPERTY_TEL_IPO = "otherIpPhone";
        public const string PROPERTY_TEL_MOBILE = "mobile";
        public const string PROPERTY_TEL_MOBILEO = "otherMobile";
        public const string PROPERTY_TEL_PAGER = "pager";
        public const string PROPERTY_TEL_PAGERO = "otherPager";
        public const string PROPERTY_TEL_PHONE = "homePhone";
        public const string PROPERTY_TEL_PHONEO = "otherHomePhone";
        private long pwdLastSet;
        private string telephone;
        private string title;
        private int userAccountControl;
        private string userName;


        public User()
        {
            this.userAccountControl = 0x10220;
        }


        internal User(DirectoryEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException();
            }
            this.Parse(entry);
        }


        internal User(SearchResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException();
            }
            this.Parse(result);
        }


        public void Add(string locationPath, string newUserPassword)
        {
            this.Add(locationPath, newUserPassword, base.iUserName, base.iPassword);
        }


        public void Add(string locationPath, string newUserPassword, string userName, string password)
        {
            if (locationPath.IndexOf("LDAP://") >= 0)
            {
                locationPath = locationPath.Substring(7);
            }
            DirectoryEntry parent = null;
            DirectoryEntry newUser = null;
            if (string.IsNullOrEmpty(locationPath))
            {
                locationPath = "CN=Users," + ParaMgr.ADFullPath;
            }
            if (!ADManager.Exists(locationPath))
            {
                throw new EntryNotExistException("指定的位置对象不存在。");
            }
            string rdn = Utils.GenerateRDNCN(base.name);
            if (ADManager.Exists(Utils.GenerateDN(rdn, locationPath)))
            {
                throw new EntryNotExistException("指定的位置下存在同名对象。");
            }
            try
            {
                parent = ADManager.GetByPath(locationPath, userName, password);
                newUser = parent.Children.Add(rdn, "user");
                Utils.SetProperty(newUser, "sAMAccountName", this.userName);
                Utils.SetProperty(newUser, "givenName", this.firstName);
                Utils.SetProperty(newUser, "sn", this.lastName);
                Utils.SetProperty(newUser, "initials", this.initials);
                Utils.SetProperty(newUser, "displayName", this.displayName);
                Utils.SetProperty(newUser, "physicalDeliveryOfficeName", this.office);
                Utils.SetProperty(newUser, "title", this.title);
                Utils.SetProperty(newUser, "manager", this.manager);
                Utils.SetProperty(newUser, "department", this.department);
                Utils.SetProperty(newUser, "telephoneNumber", this.telephone);
                Utils.SetProperty(newUser, "mobile", this.mobile);
                Utils.SetProperty(newUser, "mail", this.mail);
                Utils.SetProperty(newUser, "userPrincipalName", this.principalName);
                Utils.SetProperty(newUser, "userAccountControl", this.userAccountControl);
                Utils.SetProperty(newUser, "pwdLastSet", -1);
                newUser.CommitChanges();
                this.Parse(newUser);
                newUser.Invoke("SetPassword", new object[] { newUserPassword });
                newUser.CommitChanges();
            }
            catch (DirectoryServicesCOMException dsce)
            {
                throw dsce;
            }
            finally
            {
                if (parent != null)
                {
                    parent.Close();
                    parent.Dispose();
                }
                if (newUser != null)
                {
                    newUser.Close();
                    newUser.Dispose();
                }
            }
        }


        internal static string GeneratePrimaryGroupSID(byte[] objectSid, int primaryGroupID)
        {
            string sid1 = Utils.ConvertToOctetString(objectSid).Substring(0, 0x48);
            string sid2 = "";
            for (int i = 0; i <= 3; i++)
            {
                sid2 = sid2 + string.Format(@"\{0:x2}", primaryGroupID & 0xff);
                primaryGroupID = primaryGroupID >> 8;
            }
            return (sid1 + sid2);
        }


        public Guid GetLocation()
        {
            return this.GetLocation(base.iUserName, base.iPassword);
        }


        public Guid GetLocation(string userName, string password)
        {
            DirectoryEntry de = null;
            DirectoryEntry parent = null;
            Guid CS$1$0000;
            try
            {
                de = ADManager.GetByGuid(base.guid);
                parent = de.Parent;
                CS$1$0000 = parent.Guid;
            }
            catch
            {
                throw;
            }
            finally
            {
                if (de != null)
                {
                    de.Close();
                    de.Dispose();
                }
                if (parent != null)
                {
                    parent.Close();
                    parent.Dispose();
                }
            }
            return CS$1$0000;
        }


        public List<string> GetMemberOfDN(bool includePrimaryGroup)
        {
            return this.GetMemberOfDN(includePrimaryGroup, base.iUserName, base.iPassword);
        }


        public List<string> GetMemberOfDN(bool includePrimaryGroup, string userName, string password)
        {
            List<string> dn = new List<string>();
            if (includePrimaryGroup)
            {
                DirectoryEntry primary = ADManager.GetBySid(this.PrimaryGroupSID, userName, password);
                if (primary != null)
                {
                    dn.Add(Utils.EscapeDNBackslashedChar(primary.Properties["distinguishedName"].Value.ToString()));
                    primary.Close();
                    primary.Dispose();
                }
            }
            dn.AddRange(this.memberOf);
            return dn;
        }


        public OU GetOrganization()
        {
            return this.GetOrganization(base.iUserName, base.iPassword);
        }


        public OU GetOrganization(string userName, string password)
        {
            DirectoryEntry de = null;
            DirectoryEntry parent = null;
            OU CS$1$0000;
            try
            {
                de = ADManager.GetByGuid(base.guid);
                parent = de.Parent;
                if (parent.SchemaClassName == SchemaClass.organizationalUnit.ToString("F"))
                {
                    return new OU(parent);
                }
                CS$1$0000 = null;
            }
            catch
            {
                throw;
            }
            finally
            {
                if (de != null)
                {
                    de.Close();
                    de.Dispose();
                }
                if (parent != null)
                {
                    parent.Close();
                    parent.Dispose();
                }
            }
            return CS$1$0000;
        }


        public void Move(string newLocationPath, bool mustOU)
        {
            this.Move(newLocationPath, mustOU, base.iUserName, base.iPassword);
        }


        public void Move(string newLocationPath, bool mustOU, string userName, string password)
        {
            DirectoryEntry de = ADManager.GetByGuid(base.guid, userName, password);
            ADManager.MoveUser(de, newLocationPath, mustOU, userName, password);
            this.Parse(de);
            de.Close();
            de.Dispose();
        }


        protected override void Parse(DirectoryEntry entry)
        {
            base.Parse(entry, SchemaClass.user);
            this.userName = Utils.GetProperty(entry, "sAMAccountName");
            this.firstName = Utils.GetProperty(entry, "givenName");
            this.lastName = Utils.GetProperty(entry, "sn");
            this.initials = Utils.GetProperty(entry, "initials");
            this.displayName = Utils.GetProperty(entry, "displayName");
            this.office = Utils.GetProperty(entry, "physicalDeliveryOfficeName");
            this.title = Utils.GetProperty(entry, "title");
            this.manager = Utils.GetProperty(entry, "manager");
            this.department = Utils.GetProperty(entry, "department");
            this.telephone = Utils.GetProperty(entry, "telephoneNumber");
            this.mobile = Utils.GetProperty(entry, "mobile");
            this.mail = Utils.GetProperty(entry, "mail");
            this.principalName = Utils.GetProperty(entry, "userPrincipalName");
            this.userAccountControl = Convert.ToInt32(Utils.GetProperty(entry, "userAccountControl"));
            string primaryGroupIDStr = Utils.GetProperty(entry, "primaryGroupID");
            if (primaryGroupIDStr != null)
            {
                this.primaryGroupID = new int?(int.Parse(primaryGroupIDStr));
            }
            else
            {
                this.primaryGroupID = null;
            }
            IADsLargeInteger li = (IADsLargeInteger) entry.Properties["pwdLastSet"][0];
            this.pwdLastSet = li.HighPart + li.LowPart;
            if (entry.Properties.Contains("memberOf"))
            {
                List<string> ms = new List<string>();
                foreach (object m in entry.Properties["memberOf"])
                {
                    ms.Add(Utils.EscapeDNBackslashedChar(m.ToString()));
                }
                this.memberOf = ms.ToArray();
            }
            else
            {
                this.memberOf = new string[0];
            }
        }


        protected void Parse(SearchResult result)
        {
            base.Parse(result, SchemaClass.user);
            this.userName = Utils.GetProperty(result, "samaccountname");
            this.firstName = Utils.GetProperty(result, "givenname");
            this.lastName = Utils.GetProperty(result, "sn");
            this.initials = Utils.GetProperty(result, "initials");
            this.displayName = Utils.GetProperty(result, "displayname");
            this.office = Utils.GetProperty(result, "physicaldeliveryofficename");
            this.title = Utils.GetProperty(result, "title");
            this.manager = Utils.GetProperty(result, "manager");
            this.department = Utils.GetProperty(result, "department");
            this.telephone = Utils.GetProperty(result, "telephonenumber");
            this.mobile = Utils.GetProperty(result, "mobile");
            this.mail = Utils.GetProperty(result, "mail");
            this.principalName = Utils.GetProperty(result, "userprincipalname");
            this.userAccountControl = Convert.ToInt32(Utils.GetProperty(result, "useraccountcontrol"));
            string primaryGroupIDStr = Utils.GetProperty(result, "primarygroupid");
            if (primaryGroupIDStr != null)
            {
                this.primaryGroupID = new int?(int.Parse(primaryGroupIDStr));
            }
            else
            {
                this.primaryGroupID = null;
            }
            this.pwdLastSet = (long) result.Properties["pwdlastset"][0];
            if (result.Properties.Contains("memberof"))
            {
                List<string> ms = new List<string>();
                foreach (object m in result.Properties["memberof"])
                {
                    ms.Add(Utils.EscapeDNBackslashedChar(m.ToString()));
                }
                this.memberOf = ms.ToArray();
            }
            else
            {
                this.memberOf = new string[0];
            }
        }


        public void Remove()
        {
            this.Remove(base.iUserName, base.iPassword);
        }


        public void Remove(string userName, string password)
        {
            DirectoryEntry de = null;
            try
            {
                de = ADManager.GetByGuid(base.guid, userName, password);
                de.DeleteTree();
                de.CommitChanges();
            }
            catch (DirectoryServicesCOMException dsce)
            {
                throw dsce;
            }
            finally
            {
                if (de != null)
                {
                    de.Close();
                    de.Dispose();
                }
            }
        }


        public void SetPassword(string newPassword)
        {
            ADManager.SetUserPassword(base.guid, newPassword, base.iUserName, base.iPassword);
        }


        public void SetPassword(string newPassword, string userName, string password)
        {
            ADManager.SetUserPassword(base.guid, newPassword, userName, password);
        }


        public void Update()
        {
            this.Update(base.iUserName, base.iPassword);
        }


        public void Update(string userName, string password)
        {
            DirectoryEntry de = null;
            try
            {
                de = ADManager.GetByGuid(base.guid, userName, password);
                Utils.SetProperty(de, "sAMAccountName", this.userName);
                Utils.SetProperty(de, "givenName", this.firstName);
                Utils.SetProperty(de, "sn", this.lastName);
                Utils.SetProperty(de, "initials", this.initials);
                Utils.SetProperty(de, "displayName", this.displayName);
                Utils.SetProperty(de, "physicalDeliveryOfficeName", this.office);
                Utils.SetProperty(de, "title", this.title);
                Utils.SetProperty(de, "manager", this.manager);
                Utils.SetProperty(de, "department", this.department);
                Utils.SetProperty(de, "telephoneNumber", this.telephone);
                Utils.SetProperty(de, "mobile", this.mobile);
                Utils.SetProperty(de, "mail", this.mail);
                Utils.SetProperty(de, "userPrincipalName", this.principalName);
                Utils.SetProperty(de, "userAccountControl", this.userAccountControl);
                de.CommitChanges();
            }
            catch (DirectoryServicesCOMException dsce)
            {
                throw dsce;
            }
            finally
            {
                if (de != null)
                {
                    de.Close();
                    de.Dispose();
                }
            }
        }


        public string DisplayName
        {
            get
            {
                return this.displayName;
            }
            set
            {
                this.displayName = value;
            }
        }


        public bool DontExpirePwd
        {
            set
            {
                if (value)
                {
                    this.userAccountControl &= -65537;
                }
                else
                {
                    this.userAccountControl |= 0x10000;
                }
            }
        }


        public bool Enabled
        {
            set
            {
                if (value)
                {
                    this.userAccountControl &= -3;
                }
                else
                {
                    this.userAccountControl |= 2;
                }
            }
        }


        public string FirstName
        {
            get
            {
                return this.firstName;
            }
            set
            {
                this.firstName = value;
            }
        }


        public string Initials
        {
            get
            {
                return this.initials;
            }
            set
            {
                this.initials = value;
            }
        }


        public string LastName
        {
            get
            {
                return this.lastName;
            }
            set
            {
                this.lastName = value;
            }
        }


        public string Mail
        {
            get
            {
                return this.mail;
            }
            set
            {
                this.mail = value;
            }
        }


        public string Manager
        {
            get
            {
                return this.manager;
            }
            set
            {
                this.manager = value;
            }
        }


        public string Mobile
        {
            get
            {
                return this.mobile;
            }
            set
            {
                this.mobile = value;
            }
        }


        public bool MustChangePassword
        {
            get
            {
                return (this.pwdLastSet == 0);
            }
        }


        public string Office
        {
            get
            {
                return this.office;
            }
            set
            {
                this.office = value;
            }
        }


        public string PrimaryGroupSID
        {
            get
            {
                if (this.primaryGroupID.HasValue)
                {
                    return GeneratePrimaryGroupSID(base.objectSid, this.primaryGroupID.Value);
                }
                return null;
            }
        }


        public string PrincipalName
        {
            get
            {
                return this.principalName;
            }
            set
            {
                this.principalName = value;
            }
        }


        public string Telephone
        {
            get
            {
                return this.telephone;
            }
            set
            {
                this.telephone = value;
            }
        }


        public string Title
        {
            get
            {
                return this.title;
            }
            set
            {
                this.title = value;
            }
        }


        public int UserAccountControl
        {
            get
            {
                return this.userAccountControl;
            }
        }


        public string UserName
        {
            get
            {
                return this.userName;
            }
            set
            {
                this.userName = value;
                foreach (char i in Utils.InvalidSAMAccountNameChars)
                {
                    this.userName = this.userName.Replace(i, '_');
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值