Java访问LDAP

    技术2022-07-04  180

    1、 Java访问LDAP,所需jar包 : ldapsdk-4.1.jar

    package test; import java.util.Enumeration; import netscape.ldap.LDAPAttribute; import netscape.ldap.LDAPAttributeSet; import netscape.ldap.LDAPConnection; import netscape.ldap.LDAPEntry; import netscape.ldap.LDAPException; import netscape.ldap.LDAPSearchResults; public class LdapTest { public static void main(String[] args) { // LDAP连接对象 LDAPConnection ld = null; LDAPEntry findEntry = null; int status = -1; try { ld = new LDAPConnection(); // 连接LDAP服务器的IP及端口号 final String MY_HOST = "localhost"; final int MY_PORT = 389; // 连接LDAP服务器 ld.connect(MY_HOST, MY_PORT); // 欲查询的条目 final String ENTRYDN = "cn=admin,dc=lcl,dc=com"; // 条目的属性 final String[] attrNames = {"sn", "telephonenumber", "name", "mail"}; // LDAP查询操作结果集合 LDAPSearchResults res = ld.search(ENTRYDN, LDAPConnection.SCOPE_BASE,"objectclass=*",attrNames,false); // 循环遍历集合,获取属性名,只能遍历一次 while (res.hasMoreElements()) { try{ findEntry = res.next(); }catch (LDAPException e){ System.out.println("Error: " + e.toString()); continue; } // 条目属性名集合 LDAPAttributeSet findAttrs = findEntry.getAttributeSet(); // 属性名列表 Enumeration enumAttrs = findAttrs.getAttributes(); // 循环遍历属性名列表以获取每个属性名 while (enumAttrs.hasMoreElements()) { LDAPAttribute anAttr = (LDAPAttribute) enumAttrs.nextElement(); String attrName = anAttr.getName(); if (attrName.equals("cn")){ System.out.println("Full name:"); }else if (attrName.equals("sn")) { System.out.println("Last name (surname):"); }else if (attrName.equals("mail")) { System.out.println("Email address:"); }else if (attrName.equals("telephoneNumber")) { System.out.println("Telephone number:"); } // 断开与LDAP服务器的连接 if ((ld != null) && ld.isConnected()) { try { ld.disconnect(); } catch (LDAPException e) { System.out.println("Error: " + e.toString()); } } System.exit(status); } } }catch(Exception e){ } System.out.println("=====================成功!"); } }

     

    2、操作LDAP服务常用的命令:

         a、加密原始密码:slappasswd -h {md5} -s secret (secret是原始密码)

        b、启动 openldap :CMD 进入到C:/OpenLDAP 下,运行命令 slapd -d 1

     

     


    最新回复(0)