ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-03-06 14:01:32  阅读:122  来源: 互联网

标签:Java AD System dc Ldap println new out String


  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,AD,System,dc,Ldap,println,new,out,String
来源: https://www.cnblogs.com/LilLazy/p/14490452.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有