程序如何讀取超過1500人的通訊組成員

程序如何讀取超過1500人的通訊組成員

由於域控的LDAP策略導致一次最多能請求1500人的通訊組,解決方法就是遍歷LDAP所有的員工,然後獲取員工的memberof字段,在這裏判斷是否爲自己需要的通訊組,以此方法,便可實現獲取指定通訊組的所有成員,並獲取每個成員的詳情

下面我們貼出代碼:
Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LDAP;
using System.Configuration;
using System.DirectoryServices;
using System.Data;
using DB;
using LOG;
using MAIL;
using System.IO;
namespace 全體員工
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = System.DateTime.Now;
            Log.info("開始查詢LDAP數據"); 
            string keyword = "CN=公司全體員工,OU=通訊組,OU=******";
            List<Person> all = find_all_in_group(keyword);
            Log.info(string.Format("{0}共有{1}個成員", keyword, all.Count));
            Log.info("對比完成,保存結果");
            save("ldap_compare_oa.txt", ret1);            
            Console.ReadLine();
        }
        static bool save(string filename, string data)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false);
                sw.Write(data);
                sw.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }
        static List<Person> find_all_in_group(string keyword)
        {
            AD ad = new AD(); 
            List<Person> all = new List<Person>();
            ad.login("LDAP://" + Global.ldap, Global.usr, Global.pwd);
            ad.dir("OU=******");
            SearchResultCollection des = ad.GetDirectoryEntryAllSearch();
            foreach (SearchResult sr in des)
            {                
                DirectoryEntry de = new DirectoryEntry(sr.Path, Global.usr, Global.pwd, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                if (de.Properties["memberof"] != null)
                {
                    foreach (var item in de.Properties["memberof"])
                    {
                        if (item.ToString().Contains(keyword))
                        {
                            Person p = new Person();
                            p.name = de.Properties["cn"].Value.ToString();
                            p.path = de.Path;
                            p.username = de.Properties["sAMAccountName"].Value.ToString();
                            p.desc = de.Properties["description"] == null ? "" : de.Properties["description"].Value.ToString();
                            int control=Convert.ToInt32(de.Properties["userAccountControl"].Value.ToString());
                            p.isEnable=!ad.IsDisabled(control);
                            all.Add(p);
                            //Console.WriteLine("發現一個成員");
                            //Log.info(string.Format("發現:{0}\t{1}\t{2}\t{3}\t", p.name, p.desc, p.username, p.isEnable));
                            break;
                        }
                    }
                }
                else
                    continue;
            } 
            return all;
        }
    }
    class Person
    {
       public string name, desc, path, username;
       public bool isEnable=true;
    }
}

Global.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace 全體員工
{
    class Global
    {
        public static string ldap = ConfigurationManager.AppSettings["ldap"];
        public static string usr = ConfigurationManager.AppSettings["user"];
        public static string pwd = ConfigurationManager.AppSettings["pwd"];
        public static string baseDN = ConfigurationManager.AppSettings["ou"];
    

App.config

<configuration> 
  <appSettings>
    <add key="user" value="******@domain.cn"/>
    <add key="ldap" value="domain.cn"/>
    <add key="ou" value="OU=******"/>
    <add key="pwd" value="******"/>
    <add key="mailto" value="******@domain.cn"/>
  </appSettings>
  </configuration>

AD.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.Data;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using 全體員工;

namespace LDAP
{
    class AD
    { 
            //ADname :是域名,一般格式是:"LDAP://****";****爲域的名字(一般是大寫的英文字符串)
            //Loginname: 登錄域的用戶名(保存在域中的名字,一般是中文名字的拼音)
            //Loginpwd: 用戶名對應的登錄密碼
            //連接到域
            public static DirectoryEntry entry;
            public static DirectoryEntry root;
            //public DirectoryEntry current;

            //public static IdentityImpersonation impersonate = new IdentityImpersonation("administrator", "Mail20080318!", "hs.com");
            public enum ADS_USER_FLAG_ENUM
            {
                ///
                ///登錄腳本標誌。如果通過 ADSI LDAP 進行讀或寫操作時,該標誌失效。如果通過 ADSI WINNT,該標誌爲只讀。
                ///
                ADS_UF_SCRIPT = 0X0001,
                ///
                ///用戶帳號禁用標誌
                ///
                ADS_UF_ACCOUNTDISABLE = 0X0002,
                ///
                ///主文件夾標誌
                ///
                ADS_UF_HOMEDIR_REQUIRED = 0X0008,
                ///
                ///過期標誌
                ///
                ADS_UF_LOCKOUT = 0X0010,
                ///
                ///用戶密碼不是必須的
                ///
                ADS_UF_PASSWD_NOTREQD = 0X0020,
                ///
                ///密碼不能更改標誌
                ///
                ADS_UF_PASSWD_CANT_CHANGE = 0X0040,
                ///
                ///使用可逆的加密保存密碼
                ///
                ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
                ///
                ///本地帳號標誌
                ///
                ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,
                ///
                ///普通用戶的默認帳號類型
                ///
                ADS_UF_NORMAL_ACCOUNT = 0X0200,
                ///
                ///跨域的信任帳號標誌
                ///
                ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,
                ///
                ///工作站信任帳號標誌
                ///
                ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
                ///
                ///服務器信任帳號標誌
                ///
                ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,
                ///
                ///密碼永不過期標誌
                ///
                ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,
                ///
                /// MNS 帳號標誌
                ///
                ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
                ///
                ///交互式登錄必須使用智能卡
                ///
                ADS_UF_SMARTCARD_REQUIRED = 0X40000,
                ///
                ///當設置該標誌時,服務帳號(用戶或計算機帳號)將通過 Kerberos 委託信任
                ///
                ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
                ///
                ///當設置該標誌時,即使服務帳號是通過 Kerberos 委託信任的,敏感帳號不能被委託
                ///
                ADS_UF_NOT_DELEGATED = 0X100000,
                ///
                ///此帳號需要 DES 加密類型
                ///
                ADS_UF_USE_DES_KEY_ONLY = 0X200000,
                ///
                ///不要進行 Kerberos 預身份驗證
                ///
                ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
                ///
                ///用戶密碼過期標誌
                ///
                ADS_UF_PASSWORD_EXPIRED = 0X800000,
                ///
                ///用戶帳號可委託標誌
                ///
                ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
            }
            public bool ServerCallback(LdapConnection connection, X509Certificate certificate)
            {
                return true;
            }
            public void login(string url, string username, string password)
            {
                //LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(url));
                //con.SessionOptions.SecureSocketLayer = true;
                //con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(ServerCallback);
                //con.Credential = new NetworkCredential(username, password);
                //con.AuthType = AuthType.Basic;
                //con.Bind();
                
                entry = new DirectoryEntry(url, username, password,AuthenticationTypes.Secure|AuthenticationTypes.ServerBind);
               // entry = new DirectoryEntry(ladp, username, password, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                root = entry;
            }
            public void login(string ladp)
            {
                entry = new DirectoryEntry(ladp);
                root = entry;
            }
            public void dir(string path)
            {
                entry = entry.Children.Find(path);
            }
            public DirectoryEntry findDupOu(DirectoryEntry entry, string name)
            {
                DirectoryEntry sub_entry = GetDirectoryEntryByOU(entry, "姓名重複");
                if (sub_entry != null)
                {
                    if (checkIsNameDuplicate(sub_entry, name))
                    {
                        return findDupOu(sub_entry, name);
                    }
                    else
                    {
                        return sub_entry;
                    }
                }
                else
                {
                    return GreateOU(entry, "姓名重複");
                }

            }
            public DirectoryEntry GreateOU(DirectoryEntry entry, string ouname)
            {
                DirectoryEntry OU = entry.Children.Add("OU=" + ouname, "organizationalUnit");
                OU.CommitChanges();//執行這步出錯,錯誤提示有一個命名衝突。 (異常來自 HRESULT:0x80072037)
                return OU;
            }
            public void addusers(DataTable dt, List<String> selected)
            {
                foreach (DataRow row in dt.Rows)
                {
                    //if (row[8].ToString().Equals("帳號已存在") || row[8].ToString().Equals("OU內姓名重複"))
                    //string[] arr = selected.ToArray();
                    if (!selected.Contains(row[1].ToString()))
                    {
                        continue;
                    }
                    if (row[8].ToString().Equals("帳號已存在"))
                    {
                        DirectoryEntry ou_usr = GetOuEntryByAccount(entry, row[1].ToString());
                        if (ou_usr != null)
                        {
                            return;
                        }
                        DirectoryEntry usr = GetDirectoryEntryByAccount(root, row[1].ToString());
                        string old_ou = usr.Properties["distinguishedName"].Value.ToString();
                        usr.MoveTo(entry);
                        usr.CommitChanges();
                        SetPasswordByEntry(usr, row[4].ToString());
                        EnableUser(usr);
                        usr.Close();
                        //Log.writeline(row[0].ToString() + "(" + row[1].ToString() + ") 用戶是已經存在的用戶,已經從[" + old_ou + "]到目標OU[" + entry.Properties["distinguishedName"].Value.ToString() + "]並設置了初始密碼與啓用狀態");
                        continue;
                    }
                    DirectoryEntry user;
                    if (row[8].ToString().Equals("OU內姓名重複"))
                    {
                        //1.查找有沒有姓名重複單位,有返回進入這個單位重新檢查裏面有沒有與當前姓名重複項,如果重複就再查詢有沒有姓名重複單位,如果有則進入這個單位繼續查詢直到找到一個沒有重名的姓名重複單位,沒有就創建一個姓名重複單位,最後返回單位
                        //2.在這個單位裏創建這個新的用戶。
                        DirectoryEntry dup_ou = findDupOu(entry, row[0].ToString());
                        user = dup_ou.Children.Add("CN=" + row[0].ToString(), "user");
                        user.Properties["sAMAccountName"].Value = row[1].ToString();
                        user.Properties["displayName"].Value = row[2].ToString();
                        user.Properties["description"].Value = row[3].ToString();
                        //user.Properties["displayName"].Value = row[4];
                        user.Properties["mail"].Value = row[5].ToString();
                        user.Properties["userPrincipalName"].Value = row[1].ToString() + "@hs.handsome.com.cn";
                        user.Properties["mobile"].Value = row[6].ToString();
                        user.Properties["physicalDeliveryOfficeName"].Value = row[7].ToString();
                        user.Properties["department"].Value = row[7].ToString();
                        //user.Properties["userAccountControl"].Value = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT;
                        user.CommitChanges();
                        SetPasswordByAccount(row[1].ToString(), row[4].ToString());
                        EnableUser(user);
                        user.Close();
                        //Log.writeline(row[0].ToString() + "(" + row[1].ToString() + ")  重名用戶成功導入");
                    }
                    else
                    {
                        user = entry.Children.Add("CN=" + row[0].ToString(), "user");
                        user.Properties["sAMAccountName"].Value = row[1].ToString();
                        user.Properties["displayName"].Value = row[2].ToString();
                        user.Properties["description"].Value = row[3].ToString();
                        //user.Properties["displayName"].Value = row[4];
                        user.Properties["mail"].Value = row[5].ToString();
                        user.Properties["userPrincipalName"].Value = row[1].ToString() + "@hs.handsome.com.cn";
                        user.Properties["mobile"].Value = row[6].ToString();
                        user.Properties["physicalDeliveryOfficeName"].Value = row[7].ToString();
                        user.Properties["department"].Value = row[7].ToString();
                        //user.Properties["userAccountControl"].Value = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT;
                        user.CommitChanges();
                        SetPasswordByAccount(row[1].ToString(), row[4].ToString());
                        EnableUser(user);
                        user.Close();
                        //Log.writeline(row[0].ToString() + "(" + row[1].ToString() + ") 正常用戶成功導入");
                    }
                }
            }
            public void EnableUser(DirectoryEntry de)
            {   //impersonate.BeginImpersonate();
                de.Properties["userAccountControl"].Value = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT;
                //de.Properties["pwdLastSet"].Value = 0;
                de.CommitChanges();
                //impersonate.StopImpersonate();
                de.Close();
            }
            public void UnlockUser(DirectoryEntry de)
            {   //impersonate.BeginImpersonate();
                de.Properties["userAccountControl"].Value = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT;
                de.Properties["lockoutTime"].Clear();
                de.Properties["lockoutTime"].Add(0);
                //de.Properties["pwdLastSet"].Value = 0;
                de.CommitChanges();
                //impersonate.StopImpersonate();
                de.Close();
            }
            public void SetPasswordByAccount(string sAMAccountName, string newPassword)
            {
                DirectoryEntry de = GetDirectoryEntryByAccount(root, sAMAccountName);
                // 模擬超級管理員,以達到有權限修改用戶密碼
                //IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
                //impersonate.BeginImpersonate();
                //userEntry.Properties["UserPassword"].Add("pa$$word")
                de.Invoke("SetPassword", new object[] { newPassword });
                de.Properties["pwdLastSet"].Clear();
                de.Properties["pwdLastSet"].Add(0);
                de.CommitChanges();


                //impersonate.StopImpersonate();
                de.Close();
            }
            public void SetPasswordByEntry(DirectoryEntry usr, string newPassword)
            {
                DirectoryEntry de = usr;
                // 模擬超級管理員,以達到有權限修改用戶密碼
                //IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
                //impersonate.BeginImpersonate();
                //de.Properties["UserPassword"].Add(newPassword);
                //de.Properties["userAccountControl"].Value = 544;
                //ActiveDs.LargeInteger li=new ActiveDs.LargeInteger();
                //li.LowPart=0;
                //li.HighPart=0;
                
                de.Invoke("SetPassword", new object[] { newPassword }); 
                de.Properties["pwdLastSet"].Clear();
                de.Properties["pwdLastSet"].Add(0);
                de.CommitChanges();
                

                //impersonate.StopImpersonate();
                de.Close();
            }
            public DirectoryEntry GetContactGroupByAccount(string sAMAccountName)
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(objectClass=Group)(sAMAccountName=" + sAMAccountName + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    de = new DirectoryEntry(result.Path, Global.usr, Global.pwd, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                    return de;
                }
                catch
                {
                    return null;
                }
            }
            public DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    de = new DirectoryEntry(result.Path, Global.usr, Global.pwd, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                    return de;
                }
                catch
                {
                    return null;
                }
            }
            public DirectoryEntry GetDirectoryEntryByNo(string No)
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(description=" + No + "*))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    de = new DirectoryEntry(result.Path, Global.usr, Global.pwd, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                    return de;
                }
                catch
                {
                    return null;
                }
            }
            public SearchResultCollection GetDirectoryEntryAllSearch()
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user)))";
                deSearch.PageSize = 1000000;
                deSearch.SizeLimit = 1000000;               
                deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                try
                {
                    SearchResultCollection result = deSearch.FindAll();
                    //List<DirectoryEntry> des=new List<DirectoryEntry>();                    
                    //de = new DirectoryEntry(result.);
                    //return de;
                    return result;
                }
                catch
                {
                    return null;
                }
            }
            public DirectoryEntry GetDirectoryEntryByAccount(DirectoryEntry entry, string sAMAccountName)
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    de = new DirectoryEntry(result.Path, Global.usr, Global.pwd, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                    return de;
                }
                catch
                {
                    return null;
                }
            }
            public DirectoryEntry GetOuEntryByAccount(DirectoryEntry entry, string sAMAccountName)
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    de = new DirectoryEntry(result.Path, Global.usr, Global.pwd, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                    return de;
                }
                catch
                {
                    return null;
                }
            }            
            public DirectoryEntry GetDirectoryEntryByOU(DirectoryEntry entry, string ou)
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(objectClass=organizationalUnit)(ou=" + ou + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    de = new DirectoryEntry(result.Path, Global.usr, Global.pwd, AuthenticationTypes.Secure | AuthenticationTypes.Sealing);
                    return de;
                }
                catch
                {
                    return null;
                }
            }
            public DataSet query()
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(new DataTable());
                ds.Tables[0].Columns.AddRange(new DataColumn[] { 
                new DataColumn("c1", Type.GetType("System.String")), 
                new DataColumn("c2", Type.GetType("System.String")), 
                new DataColumn("c3", Type.GetType("System.String")), 
                new DataColumn("c4", Type.GetType("System.String")), 
                new DataColumn("c5", Type.GetType("System.String")), 
                new DataColumn("c6", Type.GetType("System.String")), 
                new DataColumn("c7", Type.GetType("System.String")), 
                new DataColumn("c8", Type.GetType("System.String")),
                new DataColumn("c9", Type.GetType("System.String"))});
                string strFilter = "(&(objectCategory=person)(objectClass=user))";
                DirectorySearcher objSearcher = new DirectorySearcher(entry, strFilter);
                //排序
                objSearcher.Sort = new SortOption("name", SortDirection.Ascending);
                SearchResultCollection src = objSearcher.FindAll();
                foreach (SearchResult sr in src)
                {
                    DataRow row = ds.Tables[0].NewRow();
                    row[0] = sr.Properties["name"][0].ToString();
                    row[1] = sr.Properties["sAMAccountName"][0].ToString();
                    row[2] = sr.Properties["displayName"][0].ToString();
                    row[3] = sr.Properties["description"].Count > 0 ? sr.Properties["description"][0] : "無";
                    row[4] = "******";
                    row[5] = sr.Properties["mail"].Count > 0 ? sr.Properties["mail"][0] : "無";
                    row[6] = sr.Properties["mobile"].Count > 0 ? sr.Properties["mobile"][0] : "無";
                    //try
                    //{
                    row[7] = sr.Properties["physicalDeliveryOfficeName"].Count > 0 ? sr.Properties["physicalDeliveryOfficeName"][0] : "無";
                    //}
                    //catch (Exception e2)
                    //{
                    //    row[7] = "";
                    //}
                    //row.AcceptChanges();                
                    ds.Tables[0].Rows.Add(row);
                }
                return ds;
            }
            //public static string convertToaccount(string name, string no)
            //{
            //    string account = "";
            //    if (name.Length <= 2)
            //    {
            //        account = PingYinHelper.ConvertToAllSpell(name) + no;
            //    }
            //    else
            //    {
            //        account = PingYinHelper.ConvertToAllSpell(name.Substring(0, 1)) + PingYinHelper.GetFirstSpell(name.Substring(1, name.Length - 1)) + no;
            //    }
            //    return account;
            //}
            public static string convertTopassword(string id)
            {
                string password = "";
                if (!string.IsNullOrEmpty(id))
                {
                    password = "hs@" + id.Substring(id.Length - 8, 8);
                }
                return password;
            }
            public bool checkIsNameDuplicate(string name)
            {
                DirectoryEntry de = entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + name + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    //de = new DirectoryEntry(result.Path);
                    if (result != null)
                        return true;
                }
                catch
                {
                    return false;
                }
                return false;
            }
            public bool checkIsNameDuplicate(DirectoryEntry sub_entry, string name)
            {
                DirectoryEntry de = sub_entry;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + name + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    //de = new DirectoryEntry(result.Path);
                    if (result != null)
                        return true;
                }
                catch
                {
                    return false;
                }
                return false;
            }
            public bool checkIsNoDuplicate(string no)
            {
                DirectoryEntry de = root;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + no + "))";
                deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    //de = new DirectoryEntry(result.Path);
                    if (result != null)
                        return true;
                }
                catch
                {
                    return false;
                }
                return false;
            }
            public DateTime ConvertFromLong(ActiveDs.LargeInteger time)
            {
                System.Type type = time.GetType();
                int highPart = time.HighPart;
                int lowPart = time.LowPart;
                long t = (long)highPart << 32 | (uint)lowPart;
                //long t = (long)highPart;
                try
                {
                    if (t != 0)
                        return System.DateTime.FromFileTime(t);
                    else
                        return System.DateTime.MinValue;
                }
                catch
                {
                    return System.DateTime.MinValue;
                }
            }
            public bool IsDisabled(int userAccContr)
            {

                if (userAccContr >= 16777216)            //TRUSTED_TO_AUTH_FOR_DELEGATION - 允許該帳戶進行委派
                {
                    userAccContr = userAccContr - 16777216;
                }
                if (userAccContr >= 8388608)            //PASSWORD_EXPIRED - (Windows 2000/Windows Server 2003) 用戶的密碼已過期
                {
                    userAccContr = userAccContr - 8388608;
                }
                if (userAccContr >= 4194304)            //DONT_REQ_PREAUTH
                {
                    userAccContr = userAccContr - 4194304;
                }
                if (userAccContr >= 2097152)            //USE_DES_KEY_ONLY - (Windows 2000/Windows Server 2003) 將此用戶限制爲僅使用數據加密標準 (DES) 加密類型的密鑰
                {
                    userAccContr = userAccContr - 2097152;
                }
                if (userAccContr >= 1048576)            //NOT_DELEGATED - 設置此標誌後,即使將服務帳戶設置爲信任其進行 Kerberos 委派,也不會將用戶的安全上下文委派給該服務
                {
                    userAccContr = userAccContr - 1048576;
                }
                if (userAccContr >= 524288)            //TRUSTED_FOR_DELEGATION - 設置此標誌後,將信任運行服務的服務帳戶(用戶或計算機帳戶)進行 Kerberos 委派。任何此類服務都可模擬請求該服務的客戶端。若要允許服務進行 Kerberos 委派,必須在服務帳戶的 userAccountControl 屬性上設置此標誌
                {
                    userAccContr = userAccContr - 524288;
                }
                if (userAccContr >= 262144)            //SMARTCARD_REQUIRED - 設置此標誌後,將強制用戶使用智能卡登錄
                {
                    userAccContr = userAccContr - 262144;
                }
                if (userAccContr >= 131072)            //MNS_LOGON_ACCOUNT - 這是 MNS 登錄帳戶
                {
                    userAccContr = userAccContr - 131072;
                }
                if (userAccContr >= 65536)            //DONT_EXPIRE_PASSWORD-密碼永不過期
                {
                    userAccContr = userAccContr - 65536;
                }
                if (userAccContr >= 2097152)            //MNS_LOGON_ACCOUNT - 這是 MNS 登錄帳戶
                {
                    userAccContr = userAccContr - 2097152;
                }
                if (userAccContr >= 8192)            //SERVER_TRUST_ACCOUNT - 這是屬於該域的域控制器的計算機帳戶
                {
                    userAccContr = userAccContr - 8192;
                }
                if (userAccContr >= 4096)            //WORKSTATION_TRUST_ACCOUNT - 這是運行 Microsoft Windows NT 4.0 Workstation、Microsoft Windows NT 4.0 Server、Microsoft Windows 2000 Professional 或 Windows 2000 Server 並且屬於該域的計算機的計算機帳戶
                {
                    userAccContr = userAccContr - 4096;
                }
                if (userAccContr >= 2048)            //INTERDOMAIN_TRUST_ACCOUNT - 對於信任其他域的系統域,此屬性允許信任該系統域的帳戶
                {
                    userAccContr = userAccContr - 2048;
                }
                if (userAccContr >= 512)            //NORMAL_ACCOUNT - 這是表示典型用戶的默認帳戶類型
                {
                    userAccContr = userAccContr - 512;
                }

                if (userAccContr >= 256)            //TEMP_DUPLICATE_ACCOUNT - 此帳戶屬於其主帳戶位於另一個域中的用戶。此帳戶爲用戶提供訪問該域的權限,但不提供訪問信任該域的任何域的權限。有時將這種帳戶稱爲“本地用戶帳戶”
                {
                    userAccContr = userAccContr - 256;
                }
                if (userAccContr >= 128)            //ENCRYPTED_TEXT_PASSWORD_ALLOWED - 用戶可以發送加密的密碼
                {
                    userAccContr = userAccContr - 128;
                }
                if (userAccContr >= 64)            //PASSWD_CANT_CHANGE - 用戶不能更改密碼。可以讀取此標誌,但不能直接設置它
                {
                    userAccContr = userAccContr - 64;
                }
                if (userAccContr >= 32)            //PASSWD_NOTREQD - 不需要密碼
                {
                    userAccContr = userAccContr - 32;
                }
                if (userAccContr >= 16)            //LOCKOUT
                {
                    userAccContr = userAccContr - 16;
                }
                if (userAccContr >= 8)            //HOMEDIR_REQUIRED - 需要主文件夾
                {
                    userAccContr = userAccContr - 8;
                }
                //if (userAccContr >= 2)            //ACCOUNTDISABLE - 禁用用戶帳戶
                //{
                //    userAccContr = userAccContr - 2;
                //}
                //if (userAccContr >= 1)            //SCRIPT - 將運行登錄腳本
                //{
                //    userAccContr = userAccContr - 1;
                //}
                if (userAccContr >= 2)
                {
                    return true;
                }
                return false;
            }
        }
     





}
發佈了47 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章