AD使用继承的成员身份获得组中的用户

时间:2013-10-17 07:12:04

标签: c# active-directory ldap

我正在尝试导出特定AD群组的成员。我有一个工作的解决方案来获得所有和过滤,但如果我想要的组有1000个可能的用户中的5个,这似乎过多..

我正朝着这个方向努力:

  public void PrintMembers(string groupname, string domain)
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, domain), groupname);
            foreach (Principal princ in group.Members)
            {
                if (princ.StructuralObjectClass == "user")
                {
                    Response.Write(UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, domain), princ.Name));
                }

            }

        }

此类工作,但未能通过基础组提供已继承成员资格的成员。

所以: “特定组1”=我让所有5名成员都好

“特定组2”=我让所有7名成员都好

“母亲团体”,上面有两组=我没有成员......

我可以迭代那些组子组,但觉得必须有另一种方式......

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

首先:@shriop point the exact answer to your question

就赏金而言,就是说:“使用LDAP协议枚举组中的用户及其子组而不递归的解决方案”。以下是Active-Directory启动Windows Server 2003 SP2并调用LDAP_MATCHING_RULE_IN_CHAIN的工作。它以递归方式(但在一个查询中)搜索组中的所有用户(小心它从安全和通讯组返回用户)。以下是C#中的ADSI用法:

static void Main(string[] args)
{
  /* Connection to Active Directory
   */
  string sFromWhere = "LDAP://SRVENTR2:389/dc=societe,dc=fr";
  DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "societe\\administrateur", "test.2011");

  /* To find all the users member of groups "Grp1"  :
   * Set the base to the groups container DN; for example root DN (dc=societe,dc=fr) 
   * Set the scope to subtree
   * Use the following filter :
   * (member:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=X)
   */
  DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
  dsLookFor.Filter = "(&(memberof:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=societe,DC=fr)(objectCategory=user))";
  dsLookFor.SearchScope = SearchScope.Subtree;
  dsLookFor.PropertiesToLoad.Add("cn");
  dsLookFor.PropertiesToLoad.Add("samAccountName");  

  SearchResultCollection srcUsers = dsLookFor.FindAll();

  /* Just show each user
   */
  foreach (SearchResult srcUser in srcUsers)
  {
    Console.WriteLine("{0}", srcUser.Path);
    Console.WriteLine("{0}", srcUser.Properties["samAccountName"][0]);
  }

  Console.ReadLine();
}

答案 1 :(得分:2)

GetMembers(true)有什么不对吗?

static void Main(string[] args)
{
    foreach (string user in GetMemberNames("My Group", "domain.local"))
    {
        Console.WriteLine(user);
    }
    Console.ReadKey();
}

public static string[] GetMemberNames(string groupname, string domain)
{
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
    using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupname))
    using (PrincipalSearchResult<Principal> results = group.GetMembers(true))
    {
        return results.OfType<UserPrincipal>().Select(u => u.SamAccountName).ToArray();
    }
}