Java通过Ldap操作AD的增删改查询

  1. package com.smnpc.util;
  2. import java.util.Hashtable;
  3. import java.util.Vector;
  4. import javax.naming.Context;
  5. import javax.naming.NamingEnumeration;
  6. import javax.naming.NamingException;
  7. import javax.naming.directory.Attribute;
  8. import javax.naming.directory.Attributes;
  9. import javax.naming.directory.BasicAttribute;
  10. import javax.naming.directory.BasicAttributes;
  11. import javax.naming.directory.DirContext;
  12. import javax.naming.directory.InitialDirContext;
  13. import javax.naming.directory.ModificationItem;
  14. import javax.naming.directory.SearchControls;
  15. import javax.naming.directory.SearchResult;
  16. import javax.naming.ldap.LdapContext;
  17. /**
  18. * Java通过Ldap操作AD的增删该查询
  19. * @author guob
  20. */
  21. public class LdapbyUser {
  22. DirContext dc = null;
  23. String root = "dc=example,dc=com"; // LDAP的根节点的DC
  24. /**
  25. *
  26. * @param dn类似于"CN=RyanHanson,dc=example,dc=com"
  27. * @param employeeID是Ad的一个员工号属性
  28. */
  29. public LdapbyUser(String dn,String employeeID) {
  30. init();
  31. // add();//添加节点
  32. // delete("ou=hi,dc=example,dc=com");//删除"ou=hi,dc=example,dc=com"节点
  33. // renameEntry("ou=new,o=neworganization,dc=example,dc=com","ou=neworganizationalUnit,o=neworganization,dc=example,dc=com");//重命名节点"ou=new,o=neworganization,dc=example,dc=com"
  34. // searchInformation("dc=example,dc=com", "", "sAMAccountName=guob");//遍历所有根节点
  35. modifyInformation(dn,employeeID);//修改
  36. // Ldapbyuserinfo("guob");//遍历指定节点的分节点
  37. close();
  38. }
  39. /**
  40. *
  41. * Ldap连接
  42. *
  43. * @return LdapContext
  44. */
  45. public void init() {
  46. Hashtable env = new Hashtable();
  47. String LDAP_URL = "ldap://xxxx:389"; // LDAP访问地址
  48. String adminName = "example\\user"; // 注意用户名的写法:domain\User或
  49. String adminPassword = "userpassword"; // 密码
  50. env.put(Context.INITIAL_CONTEXT_FACTORY,
  51. "com.sun.jndi.ldap.LdapCtxFactory");
  52. env.put(Context.PROVIDER_URL, LDAP_URL);
  53. env.put(Context.SECURITY_AUTHENTICATION, "simple");
  54. env.put(Context.SECURITY_PRINCIPAL, adminName);
  55. env.put(Context.SECURITY_CREDENTIALS, adminPassword);
  56. try {
  57. dc = new InitialDirContext(env);// 初始化上下文
  58. System.out.println("认证成功");// 这里可以改成异常抛出。
  59. } catch (javax.naming.AuthenticationException e) {
  60. System.out.println("认证失败");
  61. } catch (Exception e) {
  62. System.out.println("认证出错:" + e);
  63. }
  64. }
  65. /**
  66. * 添加
  67. */
  68. public void add(String newUserName) {
  69. try {
  70. BasicAttributes attrs = new BasicAttributes();
  71. BasicAttribute objclassSet = new BasicAttribute("objectClass");
  72. objclassSet.add("sAMAccountName");
  73. objclassSet.add("employeeID");
  74. attrs.put(objclassSet);
  75. attrs.put("ou", newUserName);
  76. dc.createSubcontext("ou=" + newUserName + "," + root, attrs);
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. System.out.println("Exception in add():" + e);
  80. }
  81. }
  82. /**
  83. * 删除
  84. *
  85. * @param dn
  86. */
  87. public void delete(String dn) {
  88. try {
  89. dc.destroySubcontext(dn);
  90. } catch (Exception e) {
  91. e.printStackTrace();
  92. System.out.println("Exception in delete():" + e);
  93. }
  94. }
  95. /**
  96. * 重命名节点
  97. *
  98. * @param oldDN
  99. * @param newDN
  100. * @return
  101. */
  102. public boolean renameEntry(String oldDN, String newDN) {
  103. try {
  104. dc.rename(oldDN, newDN);
  105. return true;
  106. } catch (NamingException ne) {
  107. System.err.println("Error: " + ne.getMessage());
  108. return false;
  109. }
  110. }
  111. /**
  112. * 修改
  113. *
  114. * @return
  115. */
  116. public boolean modifyInformation(String dn,String employeeID) {
  117. try {
  118. System.out.println("updating...\n");
  119. ModificationItem[] mods = new ModificationItem[1];
  120. /* 修改属性 */
  121. // Attribute attr0 = new BasicAttribute("employeeID", "W20110972");
  122. // mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr0);
  123. /* 删除属性 */
  124. // Attribute attr0 = new BasicAttribute("description",
  125. // "陈轶");
  126. // mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
  127. // attr0);
  128. /* 添加属性 */
  129. Attribute attr0 = new BasicAttribute("employeeID",employeeID);
  130. mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr0);
  131. /* 修改属性 */
  132. dc.modifyAttributes(dn+",dc=example,dc=com", mods);
  133. return true;
  134. } catch (NamingException e) {
  135. e.printStackTrace();
  136. System.err.println("Error: " + e.getMessage());
  137. return false;
  138. }
  139. }
  140. /**
  141. * 关闭Ldap连接
  142. */
  143. public void close() {
  144. if (dc != null) {
  145. try {
  146. dc.close();
  147. } catch (NamingException e) {
  148. System.out.println("NamingException in close():" + e);
  149. }
  150. }
  151. }
  152. /**
  153. * @param base :根节点(在这里是"dc=example,dc=com")
  154. * @param scope :搜索范围,分为"base"(本节点),"one"(单层),""(遍历)
  155. * @param filter :指定子节点(格式为"(objectclass=*)",*是指全部,你也可以指定某一特定类型的树节点)
  156. */
  157. public void searchInformation(String base, String scope, String filter) {
  158. SearchControls sc = new SearchControls();
  159. if (scope.equals("base")) {
  160. sc.setSearchScope(SearchControls.OBJECT_SCOPE);
  161. } else if (scope.equals("one")) {
  162. sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
  163. } else {
  164. sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
  165. }
  166. NamingEnumeration ne = null;
  167. try {
  168. ne = dc.search(base, filter, sc);
  169. // Use the NamingEnumeration object to cycle through
  170. // the result set.
  171. while (ne.hasMore()) {
  172. System.out.println();
  173. SearchResult sr = (SearchResult) ne.next();
  174. String name = sr.getName();
  175. if (base != null && !base.equals("")) {
  176. System.out.println("entry: " + name + "," + base);
  177. } else {
  178. System.out.println("entry: " + name);
  179. }
  180. Attributes at = sr.getAttributes();
  181. NamingEnumeration ane = at.getAll();
  182. while (ane.hasMore()) {
  183. Attribute attr = (Attribute) ane.next();
  184. String attrType = attr.getID();
  185. NamingEnumeration values = attr.getAll();
  186. Vector vals = new Vector();
  187. // Another NamingEnumeration object, this time
  188. // to iterate through attribute values.
  189. while (values.hasMore()) {
  190. Object oneVal = values.nextElement();
  191. if (oneVal instanceof String) {
  192. System.out.println(attrType + ": " + (String) oneVal);
  193. } else {
  194. System.out.println(attrType + ": " + new String((byte[]) oneVal));
  195. }
  196. }
  197. }
  198. }
  199. } catch (Exception nex) {
  200. System.err.println("Error: " + nex.getMessage());
  201. nex.printStackTrace();
  202. }
  203. }
  204. /**
  205. * 查询
  206. *
  207. * @throws NamingException
  208. */
  209. public void Ldapbyuserinfo(String userName) {
  210. // Create the search controls
  211. SearchControls searchCtls = new SearchControls();
  212. // Specify the search scope
  213. searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  214. // specify the LDAP search filter
  215. String searchFilter = "sAMAccountName=" + userName;
  216. // Specify the Base for the search 搜索域节点
  217. String searchBase = "DC=example,DC=COM";
  218. int totalResults = 0;
  219. String returnedAtts[] = { "url", "whenChanged", "employeeID", "name",
  220. "userPrincipalName", "physicalDeliveryOfficeName",
  221. "departmentNumber", "telephoneNumber", "homePhone", "mobile",
  222. "department", "sAMAccountName", "whenChanged", "mail" }; // 定制返回属性
  223. searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
  224. // searchCtls.setReturningAttributes(null); // 不定制属性,将返回所有的属性集
  225. try {
  226. NamingEnumeration answer = dc.search(searchBase, searchFilter,
  227. searchCtls);
  228. if (answer == null || answer.equals(null)) {
  229. System.out.println("answer is null");
  230. } else {
  231. System.out.println("answer not null");
  232. }
  233. while (answer.hasMoreElements()) {
  234. SearchResult sr = (SearchResult) answer.next();
  235. System.out
  236. .println("************************************************");
  237. System.out.println("getname=" + sr.getName());
  238. Attributes Attrs = sr.getAttributes();
  239. if (Attrs != null) {
  240. try {
  241. for (NamingEnumeration ne = Attrs.getAll(); ne
  242. .hasMore();) {
  243. Attribute Attr = (Attribute) ne.next();
  244. System.out.println("AttributeID="
  245. + Attr.getID().toString());
  246. // 读取属性值
  247. for (NamingEnumeration e = Attr.getAll(); e
  248. .hasMore(); totalResults++) {
  249. String user = e.next().toString(); // 接受循环遍历读取的userPrincipalName用户属性
  250. System.out.println(user);
  251. }
  252. // System.out.println(" ---------------");
  253. // // 读取属性值
  254. // Enumeration values = Attr.getAll();
  255. // if (values != null) { // 迭代
  256. // while (values.hasMoreElements()) {
  257. // System.out.println(" 2AttributeValues="
  258. // + values.nextElement());
  259. // }
  260. // }
  261. // System.out.println(" ---------------");
  262. }
  263. } catch (NamingException e) {
  264. System.err.println("Throw Exception : " + e);
  265. }
  266. }
  267. }
  268. System.out.println("Number: " + totalResults);
  269. } catch (Exception e) {
  270. e.printStackTrace();
  271. System.err.println("Throw Exception : " + e);
  272. }
  273. }
  274. /**
  275. * 主函数用于测试
  276. * @param args
  277. */
  278. public static void main(String[] args) {
  279. new LdapbyUser("CN=RyanHanson","bbs.it-home.org");
  280. }
  281. }

上一篇:JAVA用LDAP读取微软AD域里面的用户名组织架构等信息


下一篇:文件权限导致Weblogic Embedded LDAP Server启动失败解决办法