日期:2014-05-20 浏览次数:20984 次
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
public class Test10 {
public static void main(String[] args) {
new Test10().GetADInfo();
}
public void GetADInfo() {
Hashtable<String,String> HashEnv = new Hashtable<String,String>();
LdapContext ctx = null ;
String url = "ldap://127.0.0.1:389/dc=test,dc=com";
String username = "Administrator@test.com";
String adminPassword = "admin";
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
HashEnv.put(Context.SECURITY_PRINCIPAL, username);
HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword);
HashEnv.put(Context.PROVIDER_URL, url);
try {
ctx = new InitialLdapContext(HashEnv, null);
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<?> en = ctx.search("", "objectClass=User", searchCtls);
while (en != null && en.hasMoreElements()) {
Object obj = en.nextElement();
if (obj instanceof SearchResult) {
SearchResult si = (SearchResult) obj;
Attributes attrs = si.getAttributes();
if (attrs != null) {
Attribute attr = null;
attr = attrs.get("sn");
if(attr != null) System.out.println(attr.getID() + ":" + attr.get());
attr = attrs.get("sAMAccountName");
if(attr != null) System.out.println(attr.getID() + ":" + attr.get());
attr = attrs.get("givenName");
if(attr != null) System.out.println(attr.getID() + ":" + attr.get());
attr = attrs.get("mail");
if(attr != null) System.out.println(attr.getID() + ":" + attr.get());
attr = attrs.get("homePhone");
if(attr != null) System.out.println(attr.getID() + ":" + attr.get());
attr = attrs.get("telephoneNumber");
if(attr != null) System.out.println(attr.getID() + ":" + attr.get());
System.out.println();
}
}
}
} catch (NamingException e) {
e.printStackTrace();
} finally {
if(ctx != null){
try {
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
}
}
NamingEnumeration<?> en = ctx.search("", "objectClass=User", searchCtls);