Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
LDAP:如何使用C#从特定组获取用户列表?_C#_Active Directory_Ldap - Fatal编程技术网

LDAP:如何使用C#从特定组获取用户列表?

LDAP:如何使用C#从特定组获取用户列表?,c#,active-directory,ldap,C#,Active Directory,Ldap,因此,我是LDAP新手,很难找到可靠的资源 我能够建立连接,但对于如何从特定组获取用户列表,我有点不知所措。有人能帮我开始获取特定组的用户列表吗?假设您正在谈论将Active Directory作为LDAP存储,并且如果您使用的是.NET 3.5及更高版本,您应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。请在此处阅读所有相关内容: 基本上,您可以定义域上下文并在AD中轻松找到用户和/或组: // set up do

因此,我是LDAP新手,很难找到可靠的资源


我能够建立连接,但对于如何从特定组获取用户列表,我有点不知所措。有人能帮我开始获取特定组的用户列表吗?

假设您正在谈论将Active Directory作为LDAP存储,并且如果您使用的是.NET 3.5及更高版本,您应该查看
System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。请在此处阅读所有相关内容:

基本上,您可以定义域上下文并在AD中轻松找到用户和/或组:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // find the group in question
   GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

   // if found....
   if (group != null)
   {
      // iterate over members
      foreach (Principal p in group.GetMembers())
      {
          Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
          // do whatever you need to do to those members
      }
   }
}


新的S.DS.AM使得在广告中与用户和群组进行互动变得非常容易

我以这种方式编写代码以获取用户详细信息,但在System.DirectoryServices.AccountManagement.PrincipalServerDownException中出现了一个错误“System.DirectoryServices.AccountManagement.dll”,但未在用户代码中处理。我刚刚接触.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace WebApplication2
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
            {
                // find the group in question
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

                // if found....
                if (group != null)
                {
                    // iterate over members
                    foreach (Principal p in group.GetMembers())
                    {
                        Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
                        // do whatever you need to do to those members
                    }
                }
            }

        }
    }
}

用于此的库:系统。DirectoryServices

此代码将从提供的组电子邮件以及嵌套组中获取所有用户的samaccountname和mail

using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AD_LDAP
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Group Email: ");
            string groupEmail = Console.ReadLine();
            List<ADUser> members = getGroupMembers.MembersInGroup(groupEmail);
            if (members != null && members.Count > 0)
            {
                Console.WriteLine(Environment.NewLine + "Total Users: " + members.Count + Environment.NewLine);
                Console.WriteLine("*********************** Users in group ************************" + Environment.NewLine);
                Console.WriteLine("Users-Id" + "\t\t" + "Email Address" + Environment.NewLine);
                foreach (ADUser item in members)
                {
                    Console.WriteLine(item.UserId + "\t\t\t" + item.EmailAddress);
                }
            }
            else
            {
                if (members == null)
                    Console.WriteLine("Invalid group email!");
                else
                    Console.WriteLine("Group email has no members");
            }
            Console.ReadLine();
        }
    }

    class ADUser
    {
        public string UserId { get; set; }
        public string EmailAddress { get; set; }
    }

    class getGroupMembers
    {
        /// <summary>
        /// searchedGroups will contain all groups already searched, in order to
        /// prevent endless loops when there are circular structured in the groups.
        /// </summary>
        static Hashtable searchedGroups = null;

        /// <summary>
        /// "MembersInGroup" will return all users in the group passed in as a parameter
        /// The function will recursively search all nested groups.
        /// Remark: if there are multiple groups with the same name, this function will just use the first one it finds.
        /// </summary>
        /// <param name="strGroupEmail">Email of the group, which the users should be retrieved from</param>
        /// <returns>ArrayList containing the emails of all users in this group and any nested groups</returns>
        static public List<ADUser> MembersInGroup(string strGroupEmail)
        {
            List<ADUser> groupMembers = null;
            searchedGroups = new Hashtable();

            // find group
            DirectorySearcher searchGroup = new DirectorySearcher("LDAP://DC=,DC=com");
            searchGroup.Filter = ("mail=" + strGroupEmail);
            SearchResult result = searchGroup.FindOne();
            if (result != null && Convert.ToString(result.Properties["objectclass"][1]) == "group")
            {
                DirectorySearcher search = new DirectorySearcher("LDAP://DC=Your Domain Network,DC=com");
                search.Filter = String.Format("(&(objectCategory=group)(cn={0}))", Convert.ToString(result.Properties["samaccountname"][0]));
                search.PropertiesToLoad.Add("distinguishedName");
                SearchResult sru = null;
                try
                {
                    sru = search.FindOne();
                    DirectoryEntry group = sru.GetDirectoryEntry();
                    groupMembers = getUsersInGroup(group.Properties["distinguishedName"].Value.ToString());
                }
                catch { }
            }
            return groupMembers;
        }

        /// <summary>
        /// getUsersInGroup will return all users in the group passed in as a parameter
        /// The function will recursively search all nested groups.
        /// </summary>
        /// <param name="strGroupDN">"distinguishedName" of the group, which the users should be retrieved from</param>
        /// <returns>ArrayList containing the email of all users in this group and any nested groups</returns>
        private static List<ADUser> getUsersInGroup(string strGroupDN)
        {
            List<ADUser> groupMembers = new List<ADUser>();
            searchedGroups.Add(strGroupDN, strGroupDN);

            // find all users in this group
            DirectorySearcher ds = new DirectorySearcher("LDAP://DC=Your Domain Network,DC=com");
            ds.Filter = String.Format("(&(memberOf={0})(objectClass=person))", strGroupDN);
            ds.PropertiesToLoad.Add("distinguishedName");
            ds.PropertiesToLoad.Add("samaccountname");
            ds.PropertiesToLoad.Add("mail");
            foreach (SearchResult sr in ds.FindAll())
            {
                if (sr.Properties["mail"].Count > 0)
                    groupMembers.Add(new ADUser { UserId = sr.Properties["samaccountname"][0].ToString(), EmailAddress = sr.Properties["mail"][0].ToString() });
            }

            // get nested groups
            ArrayList al = getNestedGroups(strGroupDN);
            foreach (object g in al)
            {
                if (!searchedGroups.ContainsKey(g)) // only if we haven't searched this group before - avoid endless loops
                {
                    // get members in nested group
                    List<ADUser> ml = getUsersInGroup(g as string);
                    // add them to result list
                    foreach (ADUser s in ml)
                    {
                        groupMembers.Add(s);
                    }
                }
            }
            return groupMembers;
        }

        /// <summary>
        /// getNestedGroups will return an array with the "distinguishedName" of all groups contained
        /// in the group that was passed in as a parameter
        /// </summary>
        /// <param name="strGroupDN">"distinguishedName" of the group, which the nested groups should be retrieved from</param>
        /// <returns>ArrayList containing the "distinguishedName" of each group contained in the group apssed in asa parameter</returns>
        private static ArrayList getNestedGroups(string strGroupDN)
        {
            ArrayList groupMembers = new ArrayList();
            // find all nested groups in this group
            DirectorySearcher ds = new DirectorySearcher("LDAP://DC=Your Domain Network,DC=com");
            ds.Filter = String.Format("(&(memberOf={0})(objectClass=group))", strGroupDN);
            ds.PropertiesToLoad.Add("distinguishedName");
            foreach (SearchResult sr in ds.FindAll())
            {
                groupMembers.Add(sr.Properties["distinguishedName"][0].ToString());
            }
            return groupMembers;
        }
    }
}
使用系统;
使用系统集合;
使用System.Collections.Generic;
使用System.DirectoryServices;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间AD_LDAP
{
班级计划
{
静态void Main(字符串[]参数)
{
Console.WriteLine(“组电子邮件:”);
字符串groupEmail=Console.ReadLine();
列表成员=getGroupMembers.MembersGroup(groupEmail);
if(members!=null&&members.Count>0)
{
Console.WriteLine(Environment.NewLine+“总用户数:”+members.Count+Environment.NewLine);
Console.WriteLine(“*******************************组中的用户*************************”+Environment.NewLine);
Console.WriteLine(“用户Id”+“\t\t”+“电子邮件地址”+环境.NewLine);
foreach(成员中的ADUser项)
{
Console.WriteLine(item.UserId+“\t\t\t”+item.EmailAddress);
}
}
其他的
{
如果(成员==null)
Console.WriteLine(“无效的组电子邮件!”);
其他的
Console.WriteLine(“组电子邮件没有成员”);
}
Console.ReadLine();
}
}
成人班
{
公共字符串用户标识{get;set;}
公共字符串电子邮件地址{get;set;}
}
类getGroupMembers
{
/// 
///searchedGroups将包含所有已搜索的组,以便
///当组中有循环结构时,防止无止境循环。
/// 
静态哈希表searchedGroups=null;
/// 
///“MembersInGroup”将返回作为参数传入的组中的所有用户
///该函数将递归搜索所有嵌套组。
///备注:如果有多个名称相同的组,此函数将只使用它找到的第一个组。
/// 
///应从中检索用户的组的电子邮件
///包含此组和任何嵌套组中所有用户的电子邮件的ArrayList
静态公共列表成员组(字符串strGroupEmail)
{
List groupMembers=null;
searchedGroups=新哈希表();
//查找组
DirectorySearcher searchGroup=newdirectorysearcher(“LDAP://DC=,DC=com”);
searchGroup.Filter=(“mail=“+strGroupEmail”);
SearchResult=searchGroup.FindOne();
if(result!=null&&Convert.ToString(result.Properties[“objectclass”][1])==“group”)
{
DirectorySearcher search=new DirectorySearcher(“LDAP://DC=Your Domain Network,DC=com”);
search.Filter=String.Format(&(objectCategory=group)(cn={0})),Convert.ToString(result.Properties[“samaccountname”][0]);
search.PropertiesToLoad.Add(“DiscrimitedName”);
SearchResult sru=null;
尝试
{
sru=search.FindOne();
DirectoryEntry组=sru.GetDirectoryEntry();
groupMembers=getUsersInGroup(group.Properties[“DifferentizedName”].Value.ToString());
}
捕获{}
}
返回组成员;
}
/// 
///getUsersInGroup将返回作为参数传入的组中的所有用户
///该函数将递归搜索所有嵌套组。
/// 
///应从中检索用户的组的“DifferentizedName”
///包含此组和任何嵌套组中所有用户的电子邮件的ArrayList
私有静态列表getUsersInGroup(字符串strGroupDN)
{
List groupMembers=新列表();
添加(strGroupDN,strGroupDN);
//查找此组中的所有用户
DirectorySearcher ds=new DirectorySearcher(“LDAP://DC=Your Domain Network,DC=com”);
ds.Filter=String.Format((&(memberOf={0})(objectClass=person)),strGroupDN);
ds.PropertiesToLoad.Add(“区分名称”);
ds.PropertiesToLoad.Add(“samaccountname”);
ds.PropertiesToLoad.Add(“邮件”);
foreach(ds.FindAll()中的SearchResult sr)
{
如果(sr.Properties[“mail”]。计数>0)
添加(新ADUser{UserId=sr.Properties[“samaccountname”][0].ToString(),EmailAddress=sr.Properties[“mail”][0].ToString());
}
//获取嵌套组
ArrayList al=getNestedGroups(strGroupDN);
foreach(al中的对象g)