【ldap】ldap系列-java对ActiveDirectory的翻页查询

本文介绍如何在Java中实现对ActiveDirectory的翻页查询,适用于大规模ldap用户管理,提供稳定运行的代码示例,以解决网上资料不足的问题。文章还提及了高级功能如AD密码修改和证书登录,并邀请读者加入交流群进行深入讨论。
摘要由CSDN通过智能技术生成

公司有几千号员工,使用ldap管理人员账号,开发了一套ad域的管理系统,方便人员入离职账号的统一管理、运维账号统一管理、单点登录管理、现将经生产环境运行稳定的代码放出,供大家参考,网上资料太少了,很多代码都用不了,基本一步一坑,

一些高级功能,可以加qq群:669293878 或微信:codearch讨论:例如ad域密码(unicodePwd)修改、查询翻页,对ad域的jdk免证书登录等。

本章是java对微软ActiveDirectory的翻页操作:

package com.ad.ldaps;

import java.util.Hashtable;
import java.util.ArrayList;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

/**
 * 翻页获取ad账号信息
 * 
 * @author 
 *
 */
class Paged {

	static LdapContext ctx = null;

	public static void main(String[] args) {

	
		ArrayList<String> list  = new ArrayList<String>();
        Hashtable env = new Hashtable();
        String adminName = "uid=admin,ou=system";
        String adminPassword = "secret";
        String searchBase = "ou=users,dc=wimpi,dc=net";
        String searchFilter = "cn=*";
        
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

 

        //set security credentials, note using simple cleartext authentication
        env.put(Context.SECURITY_AUTHENTICATION,"simple");
        env.put(Context.SECURITY_PRINCIPAL,adminName);
        env.put(Context.SECURITY_CREDENTIALS,adminPassword);

                

        //connect to my domain controller
        env.put(Context.PROVIDER_URL, "ldap://119.23.181.57:10389");

        try {

 

            // Create the initial directory context

            ctx = new InitialLdapContext(env,null);

        

            // Create the search controls       

            SearchControls searchCtls = new SearchControls();

        

            //Specify the attributes to return

            String returnedAtts[]={"sn","givenName","mail"};

            searchCtls.setReturningAttributes(returnedAtts);

        

            //Specify the search scope

            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

 

            //Set the page size and initialize the cookie that we pass back in subsequent pages

            int pageSize = 10;

            byte[] cookie = null;

 

            //Request the paged results control

            Control[] ctls = new Control[]{new PagedResultsControl(pageSize,true)};

            ctx.setRequestControls(ctls);

 

            //initialize counter to total the results

            int totalResults = 0;
            int max_uid = 1000;
            

 

            // Search for objects using the filter
            String[] attributeNames = {"uidNumber"};
 

            do {

                NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);

 

                    // loop through the results in each page

 

                    while (results != null && results.hasMoreElements()) {

                    	NameClassPair sr = (NameClassPair)results.next();
		
		 
                    	String ncpName = sr.getName();
		                //print out the name 
		
		                System.out.println("name: " + ncpName);
		                //increment the counter
		
		                totalResults++; 
		                list.add(ncpName);
		                
		                /**
		                // 对特殊字符的DN跳过
		                //if ((ncpName + "," + searchBase).indexOf("\"") != -1 || (ncpName + "," + searchBase).indexOf("/") != -1) {continue;}
		                Attributes atts = ctx.getAttributes(ncpName + "," + searchBase, attributeNames);
		                //获取对象属性
		                Attribute uidnumber = atts.get("uidNumber");
		                if(uidnumber!=null) {
		                	String value = (String) uidnumber.get();
		                	//System.out.println(value+"uidNumber:"+uidnumber.toString());
		                	int uidn = Integer.valueOf(value);
		                	//System.out.println(ncpName+" "+uidn); 
		                	if(uidn > max_uid) {
		                		max_uid = uidn;
		                	}
		                	
		                }
		                */

                    }

    

    

            // examine the response controls

            cookie = parseControls(ctx.getResponseControls());

 

            // pass the cookie back to the server for the next page
            ctx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

 

            } while ((cookie != null) && (cookie.length != 0));

 

    

            

 

            System.out.println("Total entries: " + totalResults);

 

 

            } 

        catch (NamingException e) {

            System.err.println("Paged Search failed." + e);

            }   

        catch (java.io.IOException e) {

            System.err.println("Paged Search failed." + e);

            }


/*       Paged p = new Paged();
       System.out.println(list.size());
       int maxid = 1000;
       for(String userName : list) {
    	   searchBase = "ou=users,dc=wimpi,dc=net";
    	   try {
    		   
			int uid = p.searchByUserNameUidNumber(searchBase, userName);
			if(uid > maxid) {
				maxid = uid;
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       }
       
       maxid = maxid+1;
       
       System.out.println("最大uid:"+maxid);
       */
       if (ctx != null) {
    	   try {
			ctx.close();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       }
       

    }

 

    static byte[] parseControls(Control[] controls) throws NamingException 
{

        byte[] cookie = null;

 

        if (controls != null) {

 

                for (int i = 0; i < controls.length; i++) {

                if (controls[i] instanceof PagedResultsResponseControl) {

                    PagedResultsResponseControl prrc = (PagedResultsResponseControl)controls[i];

                    cookie = prrc.getCookie();

                    System.out.println(">>Next Page \n");

                }

                }

        }

 

        return (cookie == null) ? new byte[0] : cookie;

        }
    
    
    /**
     * @Description:指定搜索节点搜索指定域用户
     * @author erek
     * @throws Exception 
     * @date 2018-07-03
     */
    public int searchByUserNameUidNumber(String searchBase, String userName) throws Exception {
    	int uidn = 0;
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchFilter = userName;
        String returnedAtts[] = { "memberOf" }; //定制返回属性
        searchCtls.setReturningAttributes(returnedAtts); //设置返回属性集
        String[] attributeNames = { "memberOf", "uidNumber","name","objectClass"};
        
		/*
		 * try { NamingEnumeration<SearchResult> answer = dc.search(searchBase,
		 * searchFilter, searchCtls);
		 * 
		 * return answer.next(); } catch (Exception e) {
		 * System.err.println("指定搜索节点搜索指定域用户失败"); e.printStackTrace(); }
		 */
        
        NamingEnumeration<?> answer = ctx.search(searchBase, searchFilter, searchCtls);
        //NamingEnumeration<SearchResult> answer = dc.search(searchBase, searchFilter, searchCtls);
        while (answer.hasMoreElements()) {
            //SearchResult sr = (SearchResult) answer.next();
        	//System.out.println(sr.getName());
            NameClassPair ncp = (NameClassPair) answer.next();
            String ncpName = ncp.getName();
            // 对特殊字符的DN跳过
            //if ((ncpName + "," + searchBase).indexOf("\"") != -1 || (ncpName + "," + searchBase).indexOf("/") != -1) {continue;}
            Attributes atts = ctx.getAttributes(ncpName + "," + searchBase, attributeNames);
            //获取对象属性
            
            Attribute uidnumber = atts.get("uidNumber");
            /**
            if(uidnumber!=null) {
            	String value = (String) uidnumber.get();
            	System.out.println(ncpName+" "+uidnumber.toString()); 
            }
            */
            
            if(uidnumber!=null) {
            	String value = (String) uidnumber.get();
            	//System.out.println(value+"uidNumber:"+uidnumber.toString());
            	uidn = Integer.valueOf(value);
            	System.out.println(ncpName+" "+uidn); 
            }
            
            /**
            Attribute objectClassAuttribute = atts.get("objectClass");
            if(objectClassAuttribute != null) {
            	
				 	if (objectClassAuttribute.toString().indexOf("user") != -1) {
					 //获取用户是user
					 System.out.println(atts+ncpName + "," + searchBase);
				 	}
            }
            */

                       
        
            
        }
        
        return uidn;
        
    }
    

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ErekSZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值