LDAP 查询

package ldap.ceshi;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class LdapConnection {
	public static void main(String[] args) throws Exception {  
		String url = "ldap://192.168.15.88:389/";
		String domain = "dc=lingyun,dc=com";
		String user = "cn=root";
		String password = "123456";
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP 工厂
		env.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
		env.put(Context.PROVIDER_URL, url);
		env.put(Context.SECURITY_PRINCIPAL, user+","+domain); //  填DN
		env.put(Context.SECURITY_CREDENTIALS, password); // AD Password
		env.put("java.naming.ldap.attributes.binary", "objectSid objectGUID");
		LdapContext ldapCtx = null;
		try {
			ldapCtx = new InitialLdapContext(env , null);
			queryGroup(ldapCtx);	
			
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			if(ldapCtx != null) {
				try {
					ldapCtx.close();
				} catch (NamingException e) {
				}
			}
		}
	}
	//查询
	private static void queryGroup(LdapContext ldapCtx) throws NamingException {
		SearchControls searchCtls = new SearchControls();
		searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		//定位
		String searchBase = "ou=Group,dc=lingyun,dc=com";
		//查询条件
		String filter = "(&(objectClass=top)(uid=liulei))";  		
		//返回值
		String returnedAtts[] = {"givenName", "sn", "uidNumber","uid"};
		//设置查询返回值
		searchCtls.setReturningAttributes(returnedAtts);
		//查询
		//如果第三个参数为空则查询所有值
		NamingEnumeration answer = ldapCtx.search(searchBase, filter.toString(), searchCtls);

		while (answer.hasMore()) {
			 SearchResult result = answer.next();  
	            NamingEnumeration attrs = result.getAttributes().getAll();  
	            while (attrs.hasMore()) {  
	                Attribute attr = attrs.next();  
	                System.out.println(attr.getID() + "=" + attr.get());      
	            }  
	            System.out.println("============"); 
		}
		
	}

}

你可能感兴趣的:(LDAP 查询)