2013-10-23 71 views
4

我想列出Active Directory中的所有組,包括嵌套。LDAP查詢獲取組的所有組(嵌套)

有了這個,我到達頂級組:

try { 
    Hashtable<String,String> props = new Hashtable<String,String>(); 
    props.put(Context.SECURITY_AUTHENTICATION, "simple"); 
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 
    props.put(Context.PROVIDER_URL, "ldap://adserver"); 
    props.put(Context.SECURITY_PRINCIPAL, "[email protected]"); 
    props.put(Context.SECURITY_CREDENTIALS, "password"); 

    DirContext ctx = new InitialDirContext(props); 

    SearchControls cons = new SearchControls(); 
    cons.setReturningAttributes(new String[] {"cn"}); 
    cons.setSearchScope(SearchControls.ONELEVEL_SCOPE); 

    NamingEnumeration<SearchResult> answer = ctx.search("cn=users,dc=domain,dc=com", "(objectcategory=group)", cons); 
    System.out.println("AD GROUPS:"); 
    while(answer.hasMore()) { 
     SearchResult result = (SearchResult) answer.next(); 
     Attributes atts = result.getAttributes(); 
     Attribute att = atts.get("cn"); 
     String groupName = (String)att.get(); 

     //how to search for groups nested in this group 
    } 
} catch (NamingException e) { 
    e.printStackTrace(); 
} 

我如何可以獲取嵌套組?我GOOGLE了一點,發現這兩種方式:

NamingEnumeration<SearchResult> nested = ctx.search("cn=users,dc=domain,dc=com", "(&(objectClass=group)(objectCategory=group)(memberOf:1.2.840.113556.1.4.194:=cn="+groupName+"))", controls); 

NamingEnumeration<SearchResult> nested = ctx.search("cn=users,dc=domain,dc=com", "(&(objectClass=group)(objectCategory=group)(memberOf=CN="+groupName+"))", controls); 

但這沒有返回嵌套組。我究竟做錯了什麼?

回答

0

可以使用過濾器對類如下

(&(objectCategory =用戶)(的memberOf = CN = MyCustomGroup,OU = ouOfGroup,DC =子域,DC =域,DC = COM))

+1

怎麼樣的嵌套組的水平? – EJP

1

你可以嘗試下做

Attribute memberOf = srLdapUser.getAttributes().get("memberOf"); 
if (memberOf != null) { 
    for (int i = 0; i < memberOf.size(); i++) { 
     Attributes atts = ctx.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }); 
     Attribute att = atts.get("CN"); 
     groups.add((att.get().toString())); 
    } 
    System.out.println(groups.toString());` 
+1

非常好,但它只適用於一個級別。你需要一個堆棧。 – EJP

-1

嘗試改變

cons.setSearchScope(SearchControls.ONELEVEL_SCOPE); 

cons.setSearchScope(SearchControls.SUBTREE_SCOPE); 

這應該允許你搜索下的整個子樹,幷包括已指定