#JAVA操作LDAP

package com.wisdombud.unicom.monitor.ldap;

import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.Modification;
import com.unboundid.ldap.sdk.ModificationType;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldap.sdk.controls.SubentriesRequestControl;
import com.wisdombud.unicom.monitor.listener.MessageAnalyze;

public class LdapOper {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(MessageAnalyze.class);
	private LDAPConnection connection = null;
	private String bindDN = "cn=root,o=ibm,c=cn";

	private int port = 389;
	private String password = "db2admin";
	private String o = "ibm";
	private String ou = "users";
	private String ouEntry = "o=ibm,c=cn";
	private String oEntry = "o=ibm,c=cn";
	private String dcEntry = "o=ibm,c=cn";
	private String groupEntry = "cn=permitted,o=ibm,c=cn";
	private String LDAP_HOST = "127.0.0.1";
	static {
		//GlobalValues.LDAP_HOST = "127.0.0.1";
		// MonitorConfigBean config = CollectDaoFactory.getInstance()
		// .getCollectDao().findConfig();
		// if (config != null) {
		// GlobalValues.LDAP_HOST = config.getLdapIp();
		// } else {
		//
		// GlobalValues.LDAP_HOST = "127.0.0.1";
		// }
	}

	public void RunTest() {

		// LOGGER.info(this.ldapConfig.getLdapHost());
		this.openConnection();
	}

	public void openConnection() {
		if (connection == null) {
			try {
				connection = new LDAPConnection(LDAP_HOST, port,
						bindDN, password);
				LOGGER.info("connect success");
			} catch (Exception e) {
				LOGGER.info("连接LDAP出现错误:
" + e.getMessage());
			}
		}
	}

	private void createO() {
		String entryDN = this.oEntry;
		try {
			openConnection();

			SearchResultEntry entry = connection.getEntry(entryDN);
			if (entry == null) {
				ArrayList<Attribute> attributes = new ArrayList<Attribute>();
				attributes.add(new Attribute("objectClass", "top",
						"organization", "dcObject"));
				attributes.add(new Attribute("dc", this.o));
				attributes.add(new Attribute("o", this.o));
				connection.add(entryDN, attributes);
				LOGGER.info("创建o" + entryDN + "成功!");
			} else {
				LOGGER.info("o " + entryDN + "已存在!");
			}
		} catch (Exception e) {
			LOGGER.info("创建DC出现错误:
" + e.getMessage());
		}
	}

	private void createDC(String dc) {
		String entryDN = this.dcEntry;
		try {
			// 连接LDAP
			openConnection();

			SearchResultEntry entry = connection.getEntry(entryDN);
			if (entry == null) {
				// 不存在则创建
				ArrayList<Attribute> attributes = new ArrayList<Attribute>();
				attributes.add(new Attribute("objectClass", "top",
						"organization", "dcObject"));
				attributes.add(new Attribute("dc", dc));
				connection.add(entryDN, attributes);
				LOGGER.info("创建DC" + entryDN + "成功!");
			} else {
				LOGGER.info("DC " + entryDN + "已存在!");
			}
		} catch (Exception e) {
			LOGGER.info("创建DC出现错误:
" + e.getMessage());
		}
	}

	private void createOU() {
		String entryDN = this.ouEntry;
		try {
			// 连接LDAP
			openConnection();

			SearchResultEntry entry = connection.getEntry(entryDN);
			if (entry == null) {
				// 不存在则创建
				ArrayList<Attribute> attributes = new ArrayList<Attribute>();
				attributes.add(new Attribute("objectClass", "top",
						"organizationalUnit"));
				attributes.add(new Attribute("ou", this.ou));
				connection.add(entryDN, attributes);
				LOGGER.info("创建组织单元" + entryDN + "成功!");
			} else {
				LOGGER.info("组织单元" + entryDN + "已存在!");
			}
		} catch (Exception e) {
			LOGGER.info("创建组织单元出现错误:
" + e.getMessage());
		}
	}

	private void DeleteGroupMember(String userEntry) {

		try {
			SearchResultEntry entry = connection.getEntry(groupEntry);
			if (entry != null) {
				ArrayList<Modification> md = new ArrayList<Modification>();
				md.add(new Modification(ModificationType.DELETE, "member",
						userEntry));
				connection.modify(groupEntry, md);
				LOGGER.info("删除member成功:" + userEntry);
			}
		} catch (LDAPException e) {
			e.printStackTrace();
		}
	}

	private void AddGroupMember(String userEntry) {

		try {
			SearchResultEntry entry = connection.getEntry(groupEntry);
			if (entry != null) {
				ArrayList<Modification> md = new ArrayList<Modification>();
				md.add(new Modification(ModificationType.ADD, "member",
						userEntry));
				connection.modify(groupEntry, md);
				LOGGER.info("添加member成功:" + userEntry);
			}
		} catch (LDAPException e) {
			e.printStackTrace();
		}

	}

	public void createUserEntry(String user, String passwd, String ip) {
		String entryDN = "uid=" + user + "," + this.ouEntry;
		try {
			// 连接LDAP
			openConnection();

			SearchResultEntry entry = connection.getEntry(entryDN);
			if (entry == null) {
				// 不存在则创建
				ArrayList<Attribute> attributes = new ArrayList<Attribute>();

				attributes.add(new Attribute("uid", user));
				attributes.add(new Attribute("objectClass", "top",
						"organizationalPerson", "inetOrgPerson", "person"));

				attributes.add(new Attribute("userPassword", passwd));
				attributes.add(new Attribute("street", passwd));
				attributes.add(new Attribute("sn", user));
				attributes.add(new Attribute("cn", user));

				connection.add(entryDN, attributes);
				LOGGER.info("创建用户" + entryDN + "成功!");
				this.AddGroupMember(entryDN);
			} else {
				LOGGER.info("用户" + entryDN + "已存在!");
			}
		} catch (Exception e) {
			LOGGER.info("创建用户出现错误:
" + e.getMessage());
		}
	}

	public void deleteUserEntry(String user) {
		String requestDN = "uid=" + user + "," + this.ouEntry;
		try {
			// 连接LDAP
			openConnection();

			SearchResultEntry entry = connection.getEntry(requestDN);
			if (entry == null) {
				LOGGER.info(requestDN + " user:" + requestDN + "不存在");
				return;
			}
			// 删除
			connection.delete(requestDN);
			LOGGER.info("删除用户信息成功!");
			this.DeleteGroupMember(requestDN);

		} catch (Exception e) {
			LOGGER.info("删除用户信息出现错误:
" + e.getMessage());
		}
	}

	public void queryLdap(String searchDN, String filter) {
		try {
			// 连接LDAP
			openConnection();

			// 查询企业所有用户
			SearchRequest searchRequest = new SearchRequest(searchDN,
					SearchScope.SUB, "(" + filter + ")");
			searchRequest.addControl(new SubentriesRequestControl());
			SearchResult searchResult = connection.search(searchRequest);
			LOGGER.info(">>>共查询到" + searchResult.getSearchEntries().size()
					+ "条记录");
			int index = 1;
			for (SearchResultEntry entry : searchResult.getSearchEntries()) {
				LOGGER.info((index++) + "	" + entry.getDN());
			}
		} catch (Exception e) {
			LOGGER.info("查询错误,错误信息如下:
" + e.getMessage());
		}
	}

	public static void main(String[] args) {
		LdapOper loper = new LdapOper();
		System.out.println("start to create ldap user");
//		loper.createO();
//		loper.createOU();
		/*
		 * IFM_XQJZ IFM_JZBYXY IFM_JZBYMC IFM_JZBYCZC
		 * 
		 * ifm@1234
		 */
		String password = "ifm@1234";
		loper.createUserEntry("IFM_XQJZ", password, "1.1.1.1");
		loper.createUserEntry("IFM_JZBYXY", password, "1.1.1.1");
		loper.createUserEntry("IFM_JZBYMC", password, "1.1.1.1");
		loper.createUserEntry("IFM_JZBYCZC", password, "1.1.1.1");
		loper.createUserEntry("INMS_QCHMD", "inms@123", "1.1.1.1");
		// INMS_QCHMD这个也没有,密码是inms@123

	}
}

原文地址:https://www.cnblogs.com/wardensky/p/4547872.html