zoukankan      html  css  js  c++  java
  • LDAP

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