importjava.util.Properties;importjavax.naming.*;importjavax.naming.ldap.*;importjavax.naming.directory.*;publicclassClient {publicstaticvoidmain (String[] args) {
Properties env=newProperties();
String adminName="usish\\derek";
String adminPassword="dada";
String ldapURL="LDAP://192.168.40.42:389";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");//set security credentials, note using simple cleartext authenticationenv.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL, adminName);
env.put(Context.SECURITY_CREDENTIALS, adminPassword);//connect to my domain controllerenv.put(Context.PROVIDER_URL, ldapURL);try{//Create the initial directory contextLdapContext ctx=newInitialLdapContext(env,null);//Create the search controlsSearchControls searchCtls=newSearchControls();//Specify the search scopesearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);//specify the LDAP search filterString searchFilter="(&(objectCategory=person)(objectClass=user)(name=004*))";//Specify the Base for the searchString searchBase="OU=USISH,DC=usish,DC=com,DC=cn";//initialize counter to total the group membersinttotalResults=0;//Specify the attributes to returnString returnedAtts[]={"memberOf"};
searchCtls.setReturningAttributes(returnedAtts);//Search for objects using the filterNamingEnumeration answer=ctx.search(searchBase, searchFilter,
searchCtls);//Loop through the search resultswhile(answer.hasMoreElements()) {
SearchResult sr=(SearchResult) answer.next();
System.out.println(">>>"+sr.getName());//Print out the groupsAttributes attrs=sr.getAttributes();if(attrs!=null) {try{for(NamingEnumeration ae=attrs.getAll(); ae.hasMore(); ) {
Attribute attr=(Attribute) ae.next();
System.out.println("AttributeID:"+attr.getID());for(NamingEnumeration e=attr.getAll(); e.hasMore();
totalResults++) {
System.out.println("Attributes:"+e.next());
}
}
}catch(NamingException e) {
e.printStackTrace();
System.err.println("Problem listing membership:"+e);
}
}
}
System.out.println("Total groups:"+totalResults);
ctx.close();
}catch(NamingException e) {
e.printStackTrace();
System.err.println("Problem searching directory:"+e);
}
}
}