使用Java查找简单的Active Directory信息

时间:2012-04-18 15:00:12

标签: java user-interface powershell active-directory

这是我的第一篇文章,所以请保持温和。

我最近开始在工作中使用Powershell来更改AD组,查找AD信息等,但我缺少我非常喜欢Java的GUI。

是否有一种简单的方法(或代码示例),我输入目标主机名,然后返回我要求的详细信息。 AD会员组,帐户信息等?

我的Java知识并不像我的Powershell那么大,所以尽可能多的帮助会真正得到理解。

谢谢

1 个答案:

答案 0 :(得分:8)

如果您正在寻找完整的Java GUI来查询Active-Directory,您可以查看Apache Directory Studio

如果您只想使用java查询AD,下面是一个示例代码:

class TestAD 
{ 
  static DirContext ldapContext; 
  public static void main (String[] args) throws NamingException 
  { 
    try 
    { 
      System.out.println("Début du test Active Directory"); 

      Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11); 
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 
      //ldapEnv.put(Context.PROVIDER_URL,  "ldap://societe.fr:389"); 
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://dom.fr:389"); 
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); 
      //ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr"); 
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr"); 
      ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd"); 
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl"); 
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "simple"); 
      ldapContext = new InitialDirContext(ldapEnv); 

      // Create the search controls          
      SearchControls searchCtls = new SearchControls(); 

      //Specify the attributes to return 
      String returnedAtts[]={"sn","givenName", "samAccountName"}; 
      searchCtls.setReturningAttributes(returnedAtts); 

      //Specify the search scope 
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); 

      //specify the LDAP search filter 
      String searchFilter = "(&(objectClass=user))"; 

      //Specify the Base for the search 
      String searchBase = "dc=dom,dc=fr"; 
      //initialize counter to total the results 
      int totalResults = 0; 

      // Search for objects using the filter 
      NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls); 

      //Loop through the search results 
      while (answer.hasMoreElements()) 
      { 
        SearchResult sr = (SearchResult)answer.next(); 

        totalResults++; 

        System.out.println(">>>" + sr.getName()); 
        Attributes attrs = sr.getAttributes(); 
        System.out.println(">>>>>>" + attrs.get("samAccountName")); 
      } 

      System.out.println("Total results: " + totalResults); 
      ldapContext.close(); 
    } 
    catch (Exception e) 
    { 
      System.out.println(" Search error: " + e); 
      e.printStackTrace(); 
      System.exit(-1); 
    } 
  } 
}