package com.mote.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.PagedResultsControl;
import javax.naming.ldap.PagedResultsResponseControl;
public class LdAPManage {
/**
* 使用java连接AD域
* @date 2014-12-23 下午02:24:04
* @return void
* @throws 异常说明
* @param host 连接AD域服务器的ip
* @param post AD域服务器的端口
* @param username 用户名
* @param password 密码
*/
public static boolean connect(String host,String port,String username,String password, StringBuilder szRes) {
boolean bRes = false;
DirContext ctx=null;
Hashtable<String,String> HashEnv = new Hashtable<String,String>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
//HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
//username = "cn="+username+",cn=users,dc=corp,dc=sinochem,dc=com";
HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);// 默认端口389
try {
ctx = new InitialDirContext(HashEnv);// 初始化上下文
System.out.println("身份验证成功!");
szRes.append("身份验证成功!");
bRes = true;
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
szRes.append("身份验证失败!");
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
szRes.append("AD域连接失败!");
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
szRes.append("身份验证未知异常!");
} finally{
if(null!=ctx){
try {
ctx.close();
ctx=null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return bRes;
}
public static boolean connectMHAD(String username,String password, StringBuilder szRes) {
FilePropertiesUtil propertiesUtil = new FilePropertiesUtil("interfaceDomain.properties");
String host = propertiesUtil.getPropertyByName("serverIp");
String port = propertiesUtil.getPropertyByName("serverPort");
String domainName = propertiesUtil.getPropertyByName("domainName");
username = domainName + "\\"+ username;
boolean bRes = false;
DirContext ctx=null;
Hashtable<String,String> HashEnv = new Hashtable<String,String>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
//HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
//username = "cn="+username+",cn=users,dc=corp,dc=sinochem,dc=com";
HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);// 默认端口389
try {
ctx = new InitialDirContext(HashEnv);// 初始化上下文
System.out.println("身份验证成功!");
szRes.append("身份验证成功!");
bRes = true;
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
szRes.append("身份验证失败!");
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
szRes.append("AD域连接失败!");
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
szRes.append("身份验证未知异常!");
} finally{
if(null!=ctx){
try {
ctx.close();
ctx=null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return bRes;
}
@SuppressWarnings("unchecked")
public static Map<String, String> getUserList(String host,String port,String username,String password) {
Map<String, String> mapUser = new HashMap<String, String>();
//Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
//while (entries.hasNext()) {
// Map.Entry<String, String> entry = entries.next();
// System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//}
String szRes = "";
//DirContext ctx=null;
Hashtable<String,String> HashEnv = new Hashtable<String,String>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);// 默认端口389
int pageSize = 1000;
byte[] cookie = null;
try {
//ctx = new InitialDirContext(HashEnv);// 初始化上下文
LdapContext ctx = new InitialLdapContext(HashEnv, null);
System.out.println("身份验证成功!");
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });//分页读取控制---因为LDAP 默认情况只能读取1000条数据
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
//String searchFilter = "objectClass=user";
String searchFilter = "(&(objectclass=user)(sAMAccountName=*))";
//OU=中化泉州石化有限公司,OU=用户,DC=corp,DC=sinochem,DC=com
String searchBase = "OU=中化泉州石化有限公司,OU=能源事业部,OU=中国中化集团公司,OU=HROrg,DC=corp,DC=sinochem,DC=com";
//String searchBase = "OU=中化泉州石化有限公司,OU=用户,DC=corp,DC=sinochem,DC=com";
//String searchBase = "OU=用户,DC=corp,DC=sinochem,DC=com";
String returnedAtts[] = {"memberOf"};
//ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
// String returnedAtts[] = { "url", "whenChanged", "employeeID",
// "name", "userPrincipalName", "physicalDeliveryOfficeName",
// "departmentNumber", "telephoneNumber", "homePhone",
// "mobile", "department", "sAMAccountName", "whenChanged",
// "mail" }; // 定制返回属性
//String returnedAtts[] = { "memberOf", "distinguishedName",
// "Pwd-Last-Set", "User-Password", "cn" };// 定制返回属性
int totalResults = 0;
do {
NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);
// loop through the results in each page
while (results != null && results.hasMoreElements()) {
SearchResult sr = (SearchResult)results.next();
Attributes attris = sr.getAttributes();
Attribute attri = attris.get("samaccountname");
String szAttri = attri.toString();
String szsAMAccountName = szAttri.split(": ")[1];
mapUser.put((String)attri.get(), sr.getName());
//print out the name
System.out.println("szsAMAccountName:"+(String)attri.get()+ ",name: " + sr.getName());
//increment the counter
totalResults++;
}
// 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));
ctx.close();
System.out.println("Total entries: " + totalResults);
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
szRes = "身份验证失败!";
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
szRes = "AD域连接失败!";
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
szRes = "身份验证未知异常!";
}
//mapUser.clear();
//mapUser.put("test3", "test3");
return mapUser;
}
@SuppressWarnings("unchecked")
public static Map<String, String> getUserList2(String host,String port,String username,String password) {
Map<String, String> mapUser = new HashMap<String, String>();
//Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
//while (entries.hasNext()) {
// Map.Entry<String, String> entry = entries.next();
// System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//}
String szRes = "";
//DirContext ctx=null;
Hashtable<String,String> HashEnv = new Hashtable<String,String>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);// 默认端口389
int pageSize = 1000;
byte[] cookie = null;
try {
//ctx = new InitialDirContext(HashEnv);// 初始化上下文
LdapContext ctx = new InitialLdapContext(HashEnv, null);
System.out.println("身份验证成功!");
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });//分页读取控制---因为LDAP 默认情况只能读取1000条数据
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
//String searchFilter = "objectClass=user";
String searchFilter = "(&(objectclass=user)(sAMAccountName=*))";
//OU=中化泉州石化有限公司,OU=用户,DC=corp,DC=sinochem,DC=com
String searchBase = "OU=中化泉州石化有限公司,OU=能源事业部,OU=中国中化集团公司,OU=HROrg,DC=corp,DC=sinochem,DC=com";
//String searchBase = "OU=用户,DC=corp,DC=sinochem,DC=com";
String returnedAtts[] = {"memberOf"};
//ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
// String returnedAtts[] = { "url", "whenChanged", "employeeID",
// "name", "userPrincipalName", "physicalDeliveryOfficeName",
// "departmentNumber", "telephoneNumber", "homePhone",
// "mobile", "department", "sAMAccountName", "whenChanged",
// "mail" }; // 定制返回属性
//String returnedAtts[] = { "memberOf", "distinguishedName",
// "Pwd-Last-Set", "User-Password", "cn" };// 定制返回属性
int totalResults = 0;
do {
NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);
// loop through the results in each page
while (results != null && results.hasMoreElements()) {
SearchResult sr = (SearchResult)results.next();
Attributes attris = sr.getAttributes();
Attribute attri = attris.get("samaccountname");
String szAttri = attri.toString();
String szsAMAccountName = szAttri.split(": ")[1];
mapUser.put((String)attri.get(), sr.getName());
//print out the name
System.out.println("szsAMAccountName:"+(String)attri.get()+ ",name: " + sr.getName());
//increment the counter
totalResults++;
}
// 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));
ctx.close();
System.out.println("Total entries: " + totalResults);
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
szRes = "身份验证失败!";
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
szRes = "AD域连接失败!";
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
szRes = "身份验证未知异常!";
}
//mapUser.clear();
//mapUser.put("test3", "test3");
return mapUser;
}
@SuppressWarnings("unchecked")
public static Map<String, String> getOrgList(String host,String port,String username,String password) {
Map<String, String> mapOrg = new HashMap<String, String>();
//Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
//while (entries.hasNext()) {
// Map.Entry<String, String> entry = entries.next();
// System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//}
String szRes = "";
//DirContext ctx=null;
Hashtable<String,String> HashEnv = new Hashtable<String,String>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);// 默认端口389
int pageSize = 1000;
byte[] cookie = null;
try {
//ctx = new InitialDirContext(HashEnv);// 初始化上下文
LdapContext ctx = new InitialLdapContext(HashEnv, null);
System.out.println("身份验证成功!");
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });//分页读取控制---因为LDAP 默认情况只能读取1000条数据
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
//String searchFilter = "objectClass=user";
String searchFilter = "objectclass=organizationalUnit";
String searchBase = "OU=中化泉州石化有限公司,OU=用户,DC=corp,DC=sinochem,DC=com";
//String searchBase = "OU=用户,DC=corp,DC=sinochem,DC=com";
String returnedAtts[] = {"memberOf"};
int totalResults = 0;
do {
NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);
// loop through the results in each page
while (results != null && results.hasMoreElements()) {
SearchResult sr = (SearchResult)results.next();
Attributes attris = sr.getAttributes();
Attribute attricn = attris.get("cn");
Attribute attriname = attris.get("name");
//Attribute attriname = attris.get("name");
mapOrg.put((String)attricn.get(), (String)attriname.get());
//print out the name
System.out.println("attricn:" + attricn.toString() +",attriname:"+attriname.toString());
//increment the counter
totalResults++;
}
// 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));
ctx.close();
System.out.println("Total entries: " + totalResults);
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
szRes = "身份验证失败!";
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
szRes = "AD域连接失败!";
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
szRes = "身份验证未知异常!";
}
//mapUser.clear();
//mapUser.put("test3", "test3");
return mapOrg;
}
public String GetADInfo(String host,String port,String userName,String password ) {
if(userName==null){
userName = "";
}
String company = "";
String url = new String("ldap://" + host + ":" + port);
Hashtable HashEnv = new Hashtable();
// String adminName ="CN=oyxiaoyuanxy,CN=Users,DC=Hebmc,DC=com";//AD的用户名
//String adminName = "cq\\administrator"; // 注意用户名的写法:domain\User
//String adminPassword = "prd@"; // 密码
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
HashEnv.put(Context.SECURITY_PRINCIPAL, userName); // AD User
HashEnv.put(Context.SECURITY_CREDENTIALS, password); // AD Password
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put(Context.PROVIDER_URL, url);
try {
LdapContext ctx = new InitialLdapContext(HashEnv, null);
// 域节点
String searchBase = "OU=重庆烟草,DC=cq,DC=tobacco,DC=com,DC=cn";
// LDAP搜索过滤器类
String searchFilter = "objectClass=User";
// 搜索控制器
SearchControls searchCtls = new SearchControls(); // Create the
// search
// controls
// 创建搜索控制器
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Specify
// the
// search
// scope
// 设置搜索范围
// searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE); //
// Specify the search scope 设置搜索范围
// String returnedAtts[] = { "memberOf", "distinguishedName",
// "Pwd-Last-Set", "User-Password", "cn" };// 定制返回属性
String returnedAtts[] = { "company" };// 定制返回属性
// String returnedAtts[] = { "url", "whenChanged", "employeeID",
// "name", "userPrincipalName", "physicalDeliveryOfficeName",
// "departmentNumber", "telephoneNumber", "homePhone",
// "mobile", "department", "sAMAccountName", "whenChanged",
// "mail" }; // 定制返回属性
searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
// 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);// Search for objects using the filter
// 初始化搜索结果数为0
int totalResults = 0;// Specify the attributes to return
int rows = 0;
while (answer.hasMoreElements()) {// 遍历结果集
SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN
System.out.println(++rows + "************************************************");
String dn = sr.getName();
System.out.println(dn);
String match = dn.split("CN=")[1].split(",")[0];//返回格式一般是CN=ptyh,OU=专卖
System.out.println(match);
if(userName.equals(match)){
Attributes Attrs = sr.getAttributes();// 得到符合条件的属性集
if (Attrs != null) {
try {
for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore();) {
Attribute Attr = (Attribute) ne.next();// 得到下一个属性
System.out.println(" AttributeID=属性名:"+ Attr.getID().toString());
// 读取属性值
for (NamingEnumeration e = Attr.getAll(); e.hasMore(); totalResults++) {
company = e.next().toString();
System.out.println(" AttributeValues=属性值:" + company);
}
System.out.println(" ---------------");
}
} catch (NamingException e) {
System.err.println("Throw Exception : " + e);
}
}//if
}
}//while
System.out.println("************************************************");
System.out.println("Number: " + totalResults);
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
System.err.println("Throw Exception : " + e);
}
return company;
}
public boolean login() {
// 判断必填字段是否全部填写
Properties env = new Properties();
String account = "" + "@" + "";
String ldapURL = "LDAP://" + "" + ":" + "";
env.put(Context.PROVIDER_URL, ldapURL);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, account);
env.put(Context.SECURITY_CREDENTIALS, "");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//批量处理
env.put(Context.BATCHSIZE, "50");
// 连接超时设置
env.put("com.sun.jndi.ldap.connect.timeout", "3000");
// LDAP连接池
env.put("com.sun.jndi.ldap.connect.pool", "true");
// LDAP连接池最大数
env.put("com.sun.jndi.ldap.connect.pool.maxsize", "3");
// LDAP连接池优先数
env.put("com.sun.jndi.ldap.connect.pool.prefsize", "1");
// LDAP连接池超时
env.put("com.sun.jndi.ldap.connect.pool.timeout", "300000");
// LDAP连接池初始化数
env.put("com.sun.jndi.ldap.connect.pool.initsize", "1");
// LDAP连接池的认证方式
env.put("com.sun.jndi.ldap.connect.pool.authentication", "simple");
try {
//dc = new InitialLdapContext(env, null);
//logger.info("域用户" + this.username + " 登录" + account + "成功!");
return true;
} catch (Exception e) {
//logger.info("域用户" + this.username + " 登录" + account + "失败!");
return false;
}
}
public boolean ProcessLdap() {
LdapContext ldapCtx = null;
String keystore=System.getProperty("user.dir")+"\\cacerts";//将你导入的证书库文件复制放到项目文件夹下
System.setProperty("javax.net.ssl.trustStore",keystore);
String url="ldap://IP:636";//你需要连接的LDAP服务器,636为SSL端口
String username="xxxxx";//服务器用户名
String passwd="xxxxxxx";//服务器密码
Hashtable<String,String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");//LDAP FACTORY
env.put(Context.SECURITY_AUTHENTICATION,"simple");// LDAP访问安全级别
env.put(Context.SECURITY_PROTOCOL,"ssl");//链接认证服务器
env.put(Context.PROVIDER_URL,url);//LDAP地址
env.put(Context.SECURITY_PRINCIPAL,username);// 用户名
env.put(Context.SECURITY_CREDENTIALS,passwd);// 密码
try{
ldapCtx=new InitialLdapContext(env,null);
}catch(NamingException e) {
e.printStackTrace();
}
return true;
}
@SuppressWarnings("unchecked")
public static List<Map<String,String>> getADInfo(String host,String port,String adminName,String adminPassword) {
String company = "";
List<Map<String,String>> li=new ArrayList<Map<String, String>>();
List<Map<String,String>> list=new ArrayList<Map<String, String>>();
Map<String, String> namerow=new HashMap<String, String>();
String url = new String("ldap://" + host + ":" + port);
Hashtable HashEnv = new Hashtable();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User
HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put(Context.PROVIDER_URL, url);
// HashEnv.put(Context.BATCHSIZE, 2500+"");
int pageSize=980; //每次获取多少条
int total = 0;; //总共获取的条数
int total2 = 0;; //总共获取的条数
byte[] cookie = null;
try {
LdapContext ctx = new InitialLdapContext(HashEnv, null);
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });//分页读取控制---因为LDAP 默认情况只能读取1000条数据
// 域节点
/*1 姓(L) sn
2 名(F) givenName
3 显示名称(S) displayName
4 描述(D) description
5 办公室(C) physicalDeliveryOfficeName
6 英文缩写(I) initials
7 电话号码(T) telephoneNumber
8 电子邮件(M) mail
9 网页(W) wWWHomePage
10 电话号码-其它(O)... otherTelephone
11 网页-其它(R)... url
-----
1 国家/地区(O) co
2 省/自治区(V) st
3 市/县(C) l
4街道(S) streetAddress
5 邮政信箱(B) postOfficeBox
6 邮政编码(Z) postalCode
---------
1 用户登录名(U) userPrincipalName
2 用户登录名(Windows 2000 以前版本)(W) sAMAccountName
------------
1 家庭电话(M) homePhone
2 寻呼机(P) pager
3 移动电话(B) mobile
4 传真(F) facsimileTelephoneNumber
5 IP电话(I) ipPhone
6 注释 info
7 家庭电话-其它(O) otherHomePhone
8 寻呼机-其它(T) otherPager
9 移动电话-其它(B) otherMobile
10 传真-其它(E) otherFacsimileTelephoneNumber
11 IP电话-其它(R) otherIpPhone
----------
1 公司(C) company
2 部门(D) department
3 职务(J) title
4 经理-姓名(N) manager
5 直接下属(E) directReports
---------
*/
do{
String searchFilter = "objectClass=user";
//String searchBase = "OU=中化泉州石化有限公司,OU=用户,DC=corp,DC=sinochem,DC=com";
String searchBase = "OU=用户,DC=corp,DC=sinochem,DC=com";
String returnedAtts[] = {"memberOf","sAMAccountName"};
// LDAP搜索过滤器类
//(&(|(objectclass=user)(objectclass=person)(objectclass=inetOrgPerson)(objectclass=organizationalPerson)))
//String searchFilter = "(&(objectclass=user)(sAMAccountName=*))";//获取帐号
// 搜索控制器
SearchControls searchCtls = new SearchControls(); // Create the
// 创建搜索控制器
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//String[] returnedAtts = { "uSNCreated","name","userPrincipalName" };// 定制返回属性
searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
// System.out.println(searchCtls.);
// 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
int totalResults = 0;
int rows = 0;
NamingEnumeration answer =ctx.search(searchBase, searchFilter, searchCtls);
// 初始化搜索结果数为0
while (null !=answer &&answer.hasMoreElements()) {// 遍历结果集
total2++;
SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN
String dn = "total:"+String.valueOf(total2)+",Name:"+sr.getName();
System.out.println(dn);
}
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
total = prrc.getResultSize();
cookie = prrc.getCookie();
} else {
}
}
}
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
}while(cookie !=null);
ctx.close();
//System.out.println("总共:" + li.size() + "条信息.");
}catch (Exception e) {
e.printStackTrace();
return null;
}
return list;
}
public static String test2(String host,String port,String adminName,String adminPassword){
/*Hashtable env = new Hashtable();
String url = new String("ldap://" + host + ":" + port);
Hashtable HashEnv = new Hashtable();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User
HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put(Context.PROVIDER_URL, url);
try {
// Create the initial directory context
int pageSize = 980;
LdapContext ctx = new InitialLdapContext(env,null);
//Control[] ctls = new Control[]{new PagedResultsControl(pageSize,Control.CRITICAL)};
//ctx.setRequestControls(ctls);
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });//分页读取控制---因为LDAP 默认情况只能读取1000条数据
*/
String company = "";
String url = new String("ldap://" + host + ":" + port);
Hashtable HashEnv = new Hashtable();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User
HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put(Context.PROVIDER_URL, url);
// HashEnv.put(Context.BATCHSIZE, 2500+"");
int pageSize=1000; //每次获取多少条
int total = 0;; //总共获取的条数
int total2 = 0;; //总共获取的条数
byte[] cookie = null;
try {
LdapContext ctx = new InitialLdapContext(HashEnv, null);
ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });//分页读取控制---因为LDAP 默认情况只能读取1000条数据
SearchControls searchCtls = new SearchControls(); // Create the
String returnedAtts[] = {"memberOf","sAMAccountName"};
searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "objectClass=user";
String searchBase = "OU=中化泉州石化有限公司,OU=用户,DC=corp,DC=sinochem,DC=com";
//String searchBase = "OU=用户,DC=corp,DC=sinochem,DC=com";
// LDAP搜索过滤器类
//(&(|(objectclass=user)(objectclass=person)(objectclass=inetOrgPerson)(objectclass=organizationalPerson)))
//String searchFilter = "(&(objectclass=user)(sAMAccountName=*))";//获取帐号
// 搜索控制器
// 创建搜索控制器
//String[] returnedAtts = { "uSNCreated","name","userPrincipalName" };// 定制返回属性
//Set the page size and initialize the cookie that we pass back in subsequent pages
//Request the paged results control
//initialize counter to total the results
int totalResults = 0;
// Search for objects using the filter
do {
NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);
// loop through the results in each page
while (results != null && results.hasMoreElements()) {
SearchResult sr = (SearchResult)results.next();
//print out the name
System.out.println("name: " + sr.getName());
//increment the counter
totalResults++;
}
// 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));
ctx.close();
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);
}
return "";
}
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;
}
public static boolean connectMH(String host,String port,String username,String password, StringBuilder szRes) {
boolean bRes = false;
DirContext ctx=null;
Hashtable<String,String> HashEnv = new Hashtable<String,String>();
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
//HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
//username = "cn="+username+",cn=users,dc=corp,dc=sinochem,dc=com";
HashEnv.put(Context.SECURITY_PRINCIPAL, username); //AD的用户名
HashEnv.put(Context.SECURITY_CREDENTIALS, password); //AD的密码
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");//连接超时设置为3秒
HashEnv.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);// 默认端口389
try {
ctx = new InitialDirContext(HashEnv);// 初始化上下文
System.out.println("身份验证成功!");
szRes.append("身份验证成功!");
bRes = true;
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
szRes.append("身份验证失败!");
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
szRes.append("AD域连接失败!");
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
szRes.append("身份验证未知异常!");
} finally{
if(null!=ctx){
try {
ctx.close();
ctx=null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return bRes;
}
public static void main(String[] args) {
StringBuilder stb = new StringBuilder();
//LdAPManage.connect("IP", "389", "sinochem\\xueyuan", "sinochem@2015",stb);
//LdAPManage.connect("IP", "389", "admin_qz", "sinochem_2009");
//LdAPManage.getUserList("IP", "389", "sinochem\\yangqiang_qz", "Quanzhou@2016");
//LdAPManage.getADInfo("IP", "389", "sinochem\\yangqiang_qz", "Quanzhou@2016");
//LdAPManage.test2("IP", "389", "sinochem\\admin_qz", "sinochem_2009");
//LdAPManage.getUserList("IP", "389", "sinochem\\yangqiang_qz", "Quanzhou@2016");
//LdAPManage.getOrgList("IP", "389", "sinochem\\yangqiang_qz", "Quanzhou@2016");
//LdAPManage.getUserList2("IP", "389", "sinochem\\admin_qz", "sinochem_2009");
//
//LdAPManage.connectMH("172.16.104.65", "389", "sinochem\\portaltest3", "Portal33",stb);
//LdAPManage.connectMH("IP", "389", "sinochem\\xuweiqiang_qz", "Xwq@1245",stb);
//LdAPManage.connectMH("slldap.sinochem.com", "389", "sinochem\\xuweiqiang_qz", "Xwq@1245",stb);
}
}
04-17
281