简体   繁体   English

如何在JAVA中的ldapsearch中获取所有dn

[英]How to get all dn in my ldapsearch in JAVA

In Linux Shell I use the following command to get all Distinguished Names (DN) in LDAP: 在Linux Shell中,我使用以下命令来获取LDAP中的所有专有名称(DN):

ldapsearch -x -b "" -H URL -D uid=administrator,cn=admins,cn=city  -w PASS |grep dn:

My problem: How to get all DN's in Java as I did using the above command? 我的问题:如何像使用上述命令一样获取Java中的所有DN?

You can use the Java Naming and Directory Interface (JNDI) . 您可以使用Java命名和目录接口(JNDI)

Here is an example inspired from the linked tutorial : 这是一个从链接教程中得到启发的示例:

import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;

/**
 * Retrieves the DN from the search results
 */
class FullName {
  public static void printSearchEnumeration(NamingEnumeration retEnum) {
    try {
      while (retEnum.hasMore()) {
        SearchResult sr = (SearchResult) retEnum.next();
        System.out.println(">>" + sr.getNameInNamespace());
      }
    } 
    catch (NamingException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, "ldap://localhost:389");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=administrator,cn=admins,cn=city");
    env.put(Context.SECURITY_CREDENTIALS, "PASS");

    // Perform search in the entire subtree.
    SearchControls ctl = new SearchControls();
    ctl.setSearchScope(SearchControls.SUBTREE_SCOPE);

    try {
      // Create initial context
      DirContext ctx = new InitialDirContext(env);

      NamingEnumeration answer = ctx.search("", null, ctl);

      // Print the answer
      printSearchEnumeration(answer);

      // Close the context when we're done
      ctx.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM