他们是否可以使用java从AD中获取重复项

时间:2017-04-30 06:58:10

标签: java active-directory ldap

他们是否可以使用java从AD获取重复项?我看到我们可以通过对所有用户名进行分组然后检查计数> 1来在power shell中执行此操作。

https://gallery.technet.microsoft.com/scriptcenter/Find-Active-Directory-c8789b42

请帮忙:)。

1 个答案:

答案 0 :(得分:0)

您应该获得特殊类型的所有对象(例如用户,组,...)及其属性。然后检查所有对象的重复属性。为此,您可以将每个属性作为键插入到hasp映射中,并为每个对象插入属性的所有值并检查是否重复?

使用JAVA JNDI访问AD服务器,如下所示:

/**
 *  retrieve all attributes of a named object.
 * 
 */
class GetAllAttrs {
  static void printAttrs(Attributes attrs) {
    if (attrs == null) {
      System.out.println("No attributes");
    } else {
      /* Print each attribute */
      try {
        for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
          Attribute attr = (Attribute) ae.next();
          System.out.println("attribute: " + attr.getID());

          /* print each value */
          for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out
              .println("value: " + e.next()))
            ;
        }
      } 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/o=JNDITutorial");

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

      // Get all the attributes of named object
      Attributes answer = ctx.getAttributes("cn=Ted Geisel, ou=People");

      // Print the answer
      printAttrs(answer);

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

您也可以使用搜索过滤器来限制输出:

public class LdapSearch {
  public static void main(String[] args) throws Exception {
    Hashtable env = new Hashtable();

    String sp = "com.sun.jndi.ldap.LdapCtxFactory";
    env.put(Context.INITIAL_CONTEXT_FACTORY, sp);

    String ldapUrl = "ldap://localhost:389/dc=yourName, dc=com";
    env.put(Context.PROVIDER_URL, ldapUrl);

    DirContext dctx = new InitialDirContext(env);

    String base = "ou=People";

    SearchControls sc = new SearchControls();
    String[] attributeFilter = { "cn", "mail" };
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "(&(sn=W*)(l=Criteria*))";

    NamingEnumeration results = dctx.search(base, filter, sc);
    while (results.hasMore()) {
      SearchResult sr = (SearchResult) results.next();
      Attributes attrs = sr.getAttributes();

      Attribute attr = attrs.get("cn");
      System.out.print(attr.get() + ": ");
      attr = attrs.get("mail");
      System.out.println(attr.get());
    }
    dctx.close();
  }
}