c#获取AD域信息

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace DDAD_Synchronous
{
    #region --获取ad域信息示例1开始
    /// <summary>
    /// 获取ad域信息
    /// 注:如在装有AD域的环境上运行则要填写domainName,无需填写用户名和密码
    /// </summary>
    public static class AD_Test
    {
        public static string  domainName = "tgj.hinets.net";
        public static string userName = "wr";
        public static string userPwd = "Hi1Pass@word1";
        
        public static List<AdModel> list = new List<AdModel>();

        #region --是否连接到域
        /// <summary>
        /// 功能:是否连接到域
        /// </summary>
        /// <param name="domainName">域名或IP</param>
        /// <param name="userName">用户名</param>
        /// <param name="userPwd">密码</param>
        /// <param name="entry">域</param>
        /// <returns></returns>
        public static DirectoryEntry IsConnected(string domainName1, string userName1, string userPwd1, out DirectoryEntry domain)
        {
            domain = new DirectoryEntry();
            try
            {
                domain.Path = string.Format("LDAP://{0}", domainName1);
                //domain.Username = userName1;
                //domain.Password = userPwd1;
                domain.AuthenticationType = AuthenticationTypes.Secure;

                domain.RefreshCache();

                return domain;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[IsConnected方法]错误信息:" + ex.Message);
                return domain;
            }
        }
        #endregion

        #region --域中是否存在组织单位
        /// <summary>
        /// 功能:域中是否存在组织单位
        /// 作者:Wilson
        /// 时间:2012-12-15
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="ou"></param>
        /// <returns></returns>
        public static object IsExistOU(string txtRootOU, DirectoryEntry entry, out DirectoryEntry ou)
        {
            ou = new DirectoryEntry();
            try
            {
                //string txt_RootOU = "aconpayn";//根组织单位,不能为空
                //var a= entry.Children.SchemaFilter.GetEnumerator();
                ou = entry.Children.Find("OU=" + txtRootOU);

                bool response = false;
                if (ou != null) //如果根ou不为空则返回true    否则返回false
                {
                    response = true;
                }
                return ou;
                //return a;
            }
            catch (Exception ex)
            {
                //Console.WriteLine("[IsExistOU方法]错误信息:" + ex.Message);
                return "[IsExistOU方法]错误信息:" + ex.Message;
            }
        }
        #endregion

        #region --同步
        /// <summary>
        /// 功能:同步
        /// </summary>
        /// <param name="entryOU"></param>
        public static StringBuilder SyncAll(DirectoryEntry entryOU)
        {
            DirectorySearcher mySearcher = new DirectorySearcher(entryOU, "(objectclass=organizationalUnit)"); //查询组织单位                 

            DirectoryEntry root = mySearcher.SearchRoot;   //查找根OU

            SyncRootOU(root);

            StringBuilder sb = new StringBuilder();

            sb.Append("\r\nID\t帐号\t类型\t父ID\r\n");

            foreach (var item in list)
            {
                sb.AppendFormat("{0}\t{1}\t{2}\t{3}\r\n", item.Id, item.Name, item.TypeId, item.ParentId);
            }
            Console.WriteLine("同步成功");
            //LogRecord.WriteLog(sb.ToString());

            //MessageBox.Show("同步成功", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

            //Application.Exit();
            return sb;
        }
        #endregion

        #region --同步根组织单位
        /// <summary>
        /// 功能: 同步根组织单位
        /// </summary>
        /// <param name="entry"></param>
        public static void SyncRootOU(DirectoryEntry entry)
        {
            if (entry.Properties.Contains("ou") && entry.Properties.Contains("objectGUID"))
            {
                string rootOuName = entry.Properties["ou"][0].ToString();

                byte[] bGUID = entry.Properties["objectGUID"][0] as byte[];

                string id = BitConverter.ToString(bGUID);

                list.Add(new AdModel(id, rootOuName, (int)TypeEnum.OU, "0"));

                SyncSubOU(entry, id);
            }
        }
        #endregion

        #region --同步下属组织单位及下属用户
        /// <summary>
        /// 功能: 同步下属组织单位及下属用户
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="parentId"></param>
        public static void SyncSubOU(DirectoryEntry entry, string parentId)
        {
            foreach (DirectoryEntry subEntry in entry.Children)
            {
                string entrySchemaClsName = subEntry.SchemaClassName;
                
                string[] arr = subEntry.Name.Split('=');
                string categoryStr = arr[0];
                string nameStr = arr[1];
                string id = string.Empty;

                if (subEntry.Properties.Contains("objectGUID"))   //SID
                {
                    byte[] bGUID = subEntry.Properties["objectGUID"][0] as byte[]; //用户的guid

                    id = BitConverter.ToString(bGUID);
                }

                bool isExist = list.Exists(d => d.Id == id);

                switch (entrySchemaClsName) //判断获取到的是用户还是组织单位
                {
                    case "organizationalUnit":// 组织单位

                        if (!isExist)
                        {
                            //list.Add(new AdModel(id, nameStr, (int)TypeEnum.OU, parentId));  //获取根组织单位下的所有子级组织单位(注:如需要请取消注释)
                        }
                        //如果当前获取的信息为组织单位则递归,获取当前组织单位下的信息
                        SyncSubOU(subEntry, id);
                        break;
                    case "user":          //用户   注:如果获取到的信息是用户信息则查询用户信息
                        string accountName = string.Empty;
                        string user_name ="名称为空";//用户名称
                        string telephoneNumber = "电话为空";//用户电话
                        string mail = "邮箱为空";//用户邮箱
                        string department = "部门为空";//用户部门
                        //用户名称
                        if (subEntry.Properties.Contains("displayName"))
                        {
                            user_name = subEntry.Properties["displayName"][0].ToString();//用户名称
                        }
                        //用户电话
                        if (subEntry.Properties.Contains("telephoneNumber"))
                        {
                            telephoneNumber = subEntry.Properties["telephoneNumber"][0].ToString();//用户电话
                        }
                        //用户邮箱
                        if (subEntry.Properties.Contains("mail"))
                        {
                            mail = subEntry.Properties["mail"][0].ToString();//用户邮箱
                        }
                        //用户部门
                        if (subEntry.Properties.Contains("department"))
                        {
                            department = subEntry.Properties["department"][0].ToString();//用户部门
                        }
                        if (subEntry.Properties.Contains("samaccountName")) //获取用户登录名信息
                        {
                            accountName = subEntry.Properties["samaccountName"][0].ToString()+" +用户名: "+ user_name + " +电话: "+telephoneNumber+" +邮箱: "+mail+ " + 部门: "+ department;
                        }
                        

                        if (!isExist)
                        {
                            list.Add(new AdModel(id, accountName, (int)TypeEnum.USER, parentId));
                        }
                        break;
                }
            }
        }
        #endregion
    }

    #region  --枚举类型
    /// <summary>
    /// 类型
    /// </summary>
    public enum TypeEnum : int
    {
        /// <summary>
        /// 组织单位
        /// </summary>
        OU = 1,

        /// <summary>
        /// 用户
        /// </summary>
        USER = 2
    }
    #endregion

    #region --Ad域信息实体
    /// <summary>
    /// Ad域信息实体
    /// </summary>
    public class AdModel
    {
        public AdModel(string id, string name, int typeId, string parentId)
        {
            Id = id;
            Name = name;
            TypeId = typeId;
            ParentId = parentId;
        }

        /// <summary>
        /// ID
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 类型id
        /// </summary>
        public int TypeId { get; set; }

        /// <summary>
        /// 父级id
        /// </summary>
        public string ParentId { get; set; }
    }
    #endregion

    #endregion //获取ad域信息示例1结束

    #region --获取ad域信息示例2开始  注:如要使用此案例则需在装有AD域的环境上运行。    此示例需在项目中添加 System.DirectoryServices.AccountManagement引用   添加方法:引用-->程序集-->框架-->System.DirectoryServices.AccountManagement
    public class AD_Test2
    {
        /// <summary>
        /// 获取AD域名称
        /// </summary>
        public static string GetADName()
        {
            #region //获取AD域名称
            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            string hostName = ipGlobalProperties.HostName;
            string domainName = ipGlobalProperties.DomainName;
            #endregion

            #region --获取指定域中的用户查找对象
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName);
            UserPrincipal userPrincipal = new UserPrincipal(principalContext);
            PrincipalSearcher principalSearcher = new PrincipalSearcher(userPrincipal);
            #endregion

            #region//查询域中用户及其信息
            StringBuilder sb = new StringBuilder();
            int i = 0;
            foreach (UserPrincipal userPrincipalSearchResult in principalSearcher.FindAll())
            {
                i++;
                sb.AppendLine(string.Format("----------------------------------第"+i+"个用户---------------------------------"));
                //sb.AppendLine(string.Format("UPN:{0}", userPrincipalSearchResult.UserPrincipalName));
                //sb.AppendLine(string.Format("姓氏Last Name:{0}", userPrincipalSearchResult.Surname));
                //sb.AppendLine(string.Format("中间名:{0}", userPrincipalSearchResult.MiddleName));
                // sb.AppendLine(string.Format("Given Name/First Name名:{0}", userPrincipalSearchResult.GivenName));
                sb.AppendLine(string.Format("名称:{0}", userPrincipalSearchResult.Name));
                //sb.AppendLine(string.Format("上次登录时间:{0}", userPrincipalSearchResult.LastLogon));
                sb.AppendLine(string.Format("用户电话:{0}", userPrincipalSearchResult.VoiceTelephoneNumber));
                sb.AppendLine(string.Format("用户邮箱:{0}", userPrincipalSearchResult.EmailAddress));
                sb.AppendLine(string.Format("工作站列表:{0}", userPrincipalSearchResult.PermittedWorkstations));
                sb.AppendLine(string.Format("此账户主目录:{0}", userPrincipalSearchResult.HomeDirectory));
                sb.AppendLine(string.Format("雇员id:{0}", userPrincipalSearchResult.EmployeeId));
                sb.AppendLine(string.Format("主体名称:{0}", userPrincipalSearchResult.DistinguishedName));
                sb.AppendLine(string.Format("主体说明:{0}", userPrincipalSearchResult.Description));
                sb.AppendLine(string.Format("主题显示名称:{0}", userPrincipalSearchResult.DisplayName));
                sb.AppendLine(string.Format("与主体关联的主体上下文:{0}", userPrincipalSearchResult.Context));
                sb.AppendLine(string.Format("获取或设置此账户的主目录:{0}", userPrincipalSearchResult.HomeDirectory));
                sb.AppendLine(string.Format("用户主体的中间名:{0}", userPrincipalSearchResult.MiddleName));
                sb.AppendLine(string.Format("主体的SAM账户名:{0}", userPrincipalSearchResult.SamAccountName));
                sb.AppendLine(string.Format("主体的安全id  Sid:{0}", userPrincipalSearchResult.Sid));
                sb.AppendLine(string.Format("----------------------------------结束分界线---------------------------------"));
                sb.AppendLine(string.Format(""));
            }
            userPrincipal.Dispose();
            Console.WriteLine(sb.ToString());
            #endregion
            return domainName ;
        }
    }
    #endregion //获取ad域信息示例2结束
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值