zoukankan      html  css  js  c++  java
  • LDAP学习

    LDAP概述

    目录系统是关于某些类别的对象(例如人)的信息列表。目录可以用于查找特定对象的信息,也可以反方向查找满足特定需求的对象。 企业中的员工通讯录就是一个目录系统。目录访问协议(directory access protocol)就是用来访问目录中数据的标准化方式。最广泛使用的是 轻量级目录访问协议(lightweight directory access protocol,LDAP),openldap是LDAP的一个开源实现。

    LDAP数据模型

    在LDAP目录中存储的是类似于面向对象语言中 对象 的条目(entry)。每个条目必须有一个能标示自己的 可区别名称(distinguished name, DN),DN又由一组 相对可区别名称(relative DN, RDN)组成。
    例如(下面的例子都存在于我们后面将要搭建的openldap环境中):
    cn=user01,ou=People,dc=massclouds,dc=com
    这个DN唯一标示的条目代表了目录中的一个人。 其中各个RDN的含义是:
    cn: common name(s) for which the entity is known by
    ou: organizational unit this object belongs to
    dc: domain component

    就像面向对象语言中的对象一样,条目 也有所属的类,也拥有自己的属性。条目可以属于多个类,这些类也拥有继承关系。 而条目中的属性就是定义在这些类中的。关于objectclass 、属性的规则是定义在schema中的。

    下面是定义一个条目的LDIF(LDAP Data Interchange Format, LDAP数据交换格式):

    dn: cn=user01,ou=People,dc=massclouds,dc=com
    cn: user01
    gidnumber: 500
    homedirectory: /home/user01
    loginshell: /bin/bash
    objectclass: inetOrgPerson
    objectclass: posixAccount
    objectclass: top
    sn: user01
    title:  
    uid: user01
    uidnumber: 836031732
    userpassword: {SSHA}25vgYD/sRglAUSKLKfIU7hya9Kp/cFUS
    

     上面的例子中,表示user01的条目属于三个objectclass: inetOrgPerson 、posixAccount和top。 objectclass分为 结构型、辅助型和抽象型,每个条目必须要属于一个结构型的objectclass。 在objectclass中定义了必须的属性和可选的属性,条目如果属于某个objectclass,那么就必须要有这个objectclass所有的必须属性。

    条目按照它们的DN组织成一颗 目录信息数(Directory Intermation Tree, DIT),树的叶子节点通常表示特定的对象,而内部节点表示组织、部门等上层信息。 一个节点必然会包含它父节点的所有RDN。

    上面所展示的就是一个DIT,叶子节点分别表示 管理员节点(cn=ldapadm),具体的用户组(cn=ldapusers)和具体的用户(cn=a_001),而其他内部节点则是用来分类管理这些叶子节点的上层节点。从这颗DIT中我们可以得到user01完整的dn为:cn=user01,ou=People,dc=massclouds,dc=com, 而People这个内部节点的完整dn为: ou=People,dc=massclouds,dc=com, 子节点完全拥有父节点的所有rdn。

    搭建OpenLDAP环境

    在网上可以找到很多搭建openldap的文章,但很多都是针对比较旧的版本的。 下面的步骤基本来自 Step by Step OpenLDAPServer Configuration on CentOS 7 / RHEL 7  这篇文章,这里记录下来留作自己参考,你也可以直接阅读原文就好了。

     环境:

       openladp-server: 192.168.107.177 (centos 7)

       openldap-client :   192.168.107.178 (centos 7)

    搭建服务端:

    安装软件:

    yum -y install OpenLDAPcompat-OpenLDAPopenldap-clients openldap-servers openldap-servers-sql openldap-devel

    启动服务和开机启动(slapd是openldap-servers的服务名):

    systemctl start slapd.service
    systemctl enable slapd.service

     389是openldap的默认端口,验证服务是否启动:

    netstat -altpn | grep 389
    tcp        0      0 0.0.0.0:389             0.0.0.0:*               LISTEN      4358/slapd          
    tcp6       0      0 :::389                  :::*                    LISTEN      4358/slapd  
    

     OpenLDAP有一个创建密码的工具 slappasswd,在下面介绍jldap的内容中会有一个 算法逻辑相同的 java实现。

    -h 指定加密算法 {MD5} {ssha}等 -s 指定希望加密的明文密码

    slappasswd -h {ssha} -s 123456
    {SSHA}aMRnRqs2Kicc0ZtSsaU2B3Duhc2CFxO6

     我们需要使用slappasswd生成一个管理员密码,例如上面由123456生成的那个,并把它保存起来,后面会用到。

    配置OpenLDAPserver:

    OpenLDAPservers 的配置文件在/etc/openldap/slapd.d/下面。我们需要修改“olcSuffix”和“oldRootDN”。

    olcSuffix:ldap数据库前缀,它是LDAP server提供信息的域名,简单来讲就是你当前机器的域名,我的环境为massclouds.com。

    olcRootDN: LDAP上超级管理员的DN

    olcRootPW: RootDN的密码

    我们其实想要修改的内容就存在于/etc/openldap/slapd.d/cn=config/olcDatabase={2}hdb.ldif 中,但是直接修改是OpenLDAP不建议的,所以我们通过编写一个LDIF文件来修改。

    编辑db.ldif 如下:

    dn: olcDatabase={2}hdb,cn=config
    changetype: modify
    replace: olcSuffix
    olcSuffix: dc=massclouds,dc=com
    
    dn: olcDatabase={2}hdb,cn=config
    changetype: modify
    replace: olcRootDN
    olcRootDN: cn=ldapadm,dc=massclouds,dc=com
    
    dn: olcDatabase={2}hdb,cn=config
    changetype: modify
    replace: olcRootPW
    #这里就是刚才保存下来的那个加密后的密码
    olcRootPW: {SSHA}o9CdHYvIqTp2o5RvA4Ci+wBUTwMHfN9J
    
    

     注意replace: olcRootPW中冒号后面有一个空格,并且最后面也不要有任何空格或制表符。执行以下命令:

    ldapmodify -Y EXTERNAL  -H ldapi:/// -f db.ldif
    

     执行完成后,你会发现/etc/openldap/slapd.d/cn=config/olcDatabase={2}hdb.ldif的内容已经发生了变化。

    修改/etc/openldap/slapd.d/cn=config/olcDatabase={1}monitor.ldif (不要手动编辑)文件来只允许root(ldapadm)可以监控访问。编辑monitor.ldif 如下:

    dn: olcDatabase={1}monitor,cn=config
    changetype: modify
    replace: olcAccess
    olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external, cn=auth" read by dn.base="cn=ldapadm,dc=massclouds,dc=com" read by * none

     执行:

    ldapmodify -Y EXTERNAL  -H ldapi:/// -f monitor.ldif

     创建LDAP证书

     我们为LDAP服务器创建一个自签发的证书,下面的命令将在/etc/openldap/certs/目录中生成证书和私钥。

    [root@localhost ~]#  openssl req -new -x509 -nodes -out /etc/openldap/certs/masscloudsldapcert.pem -keyout /etc/openldap/certs/masscloudsldapkey.pem -days 365
    
    
    Generating a 2048 bit RSA private key
    ........................................................+++
    ....................................+++
    writing new private key to '/etc/openldap/certs/masscloudsldapkey.pem'
    -----
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [XX]:CN
    State or Province Name (full name) []:Shandong
    Locality Name (eg, city) [Default City]:jinan 
    Organization Name (eg, company) [Default Company Ltd]:Massclouds  Technology Co., Ltd                                                
    Organizational Unit Name (eg, section) []:
    Common Name (eg, your name or your server's hostname) []:
    Email Address []:
    
    

     修改生成的证书和私钥的权限

    chown -R ldap:ldap /etc/openldap/certs/*.pem

     有了证书后,我们就可以配置OpenLDAP使用我们的证书安全通信了。编辑certs.ldif, 如下:

    dn: cn=config
    changetype: modify
    replace: olcTLSCertificateFile
    olcTLSCertificateFile: /etc/openldap/certs/masscloudsldapcert.pem
    
    dn: cn=config
    changetype: modify
    replace: olcTLSCertificateKeyFile
    olcTLSCertificateKeyFile: /etc/openldap/certs/masscloudsldapkey.pem

     执行:

    ldapmodify -Y EXTERNAL  -H ldapi:/// -f certs.ldif 

     配置这些之后,我们可以验证配置是否正确:

    [root@localhost ~]# slaptest -u
    config file testing succeeded
    

    建立LDAP数据库:

    复制下面的这个数据库配置文件到/var/lib/ldap中,并更改文件权限。

    cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG
    chown ldap:ldap /var/lib/ldap/*
    

    添加cosine和nis LDAP schema (这些schema中定义了基本的objectclass,attribute)

    ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif
    ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif 
    ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif
    

     创建base.ldif,如下:

    #根节点
    dn: dc=massclouds,dc=com
    dc: massclouds
    objectClass: top
    objectClass: domain
    
    #管理员节点
    dn: cn=ldapadm ,dc=massclouds,dc=com
    objectClass: organizationalRole
    cn: ldapadm
    description: LDAP Manager
    
    #管理所有人员的上层节点,它的子节点就是一个个表示具体人的叶子节点
    dn: ou=People,dc=massclouds,dc=com
    objectClass: organizationalUnit
    ou: People
    
    #管理所有组的上层节点,它的子节点就是一个个表示具体组的叶子节点
    dn: ou=Group,dc=massclouds,dc=com
    objectClass: organizationalUnit
    ou: Group
    

     我们看一下上面这个文件,这里面定义的四个节点就构成了目录信息数(DIT)的大体结构,下面我们使用root(ldapadm)来将这些节点加入到ldap中。

    [root@localhost ~]# ldapadd -x -W -D "cn=ldapadm,dc=massclouds,dc=com" -f base.ldif 
    
    Enter LDAP Password: 
    adding new entry "dc=massclouds,dc=com"
    adding new entry "cn=ldapadm ,dc=massclouds,dc=com"
    adding new entry "ou=People,dc=massclouds,dc=com"
    adding new entry "ou=Group,dc=massclouds,dc=com"
    

     上面提示输入的就是在最开始我们为root(ldapadm)设置的那个密码。我们看到输出信息中已经提示为我们的目录信息数加入了四个节点。

    下面我们来创建表示具体组和人的叶子节点,创建group.ldif(我们后面会讲到openldap的web控制台phpldapadmin,在其中我们可以更方便的执行节点操作)

    dn: cn=ldapusers,ou=Group,dc=massclouds,dc=com
    cn: ldapusers
    gidnumber: 500
    objectclass: posixGroup
    objectclass: top
    

     执行:

    ldapadd -x -W -D "cn=ldapadm,dc=massclouds,dc=com" -f group.ldif

     创建 user01.ldif,如下:

    dn: cn=user01,ou=People,dc=massclouds,dc=com
    cn: user01
    gidnumber: 500
    homedirectory: /home/user01
    loginshell: /bin/bash
    objectclass: inetOrgPerson
    objectclass: posixAccount
    objectclass: top
    sn: user01
    uid: user01
    uidnumber: 836031732
    userpassword: {SSHA}wslbkdgQZUAnv+MvYgR3U1DGxSR8hwSL
    

     执行:

    ldapadd -x -W -D "cn=ldapadm,dc=massclouds,dc=com" -f user01.ldif

     到此为止,我们就一共创建了六个节点,我们到phpldapadmin上面看一下DIT是什么样的:

    另外还有 ldapsearch ldapdelete 等命令拥有查找、删除 等操作,就不介绍了。

    配置ldap日志

    配置Rsyslog来记录LDAP事件到日志文件 /var/log/ldap.log中。修改/etc/rsyslog.conf在后面加上一句:

    local4.* /var/log/ldap.log

     然后重启rsyslog服务,并重启slapd让ldap有事件发生,就会看到生成ldap.log文件了。

    systemctl restart rsyslog
    systemctl restart slapd
    

     最后不要忘记放开防火墙:

    firewall-cmd --permanent --add-service=ldap
    firewall-cmd --reload
    

     到此为止我们就已经搭建完成OpenLDAP的服务端了,下面我们来搭建OpenLDAP的客户端,这里需要说明一下,我们这里将使用OpenLDAP来集中管理客户端的账号,也就是说存在于server上的用户(例如上面创建的那个user01)可以直接在 client上登录。

    安装软件

    登录到客户端环境中,执行:

    yum install -y openldap-clients nss-pam-ldapd

    执行下面的命令来将客户端机器加入到LDAP server中来认证。 把下面的“192.168.107.177” 替换为你自己的LDAP server的ip或者hostname。

    authconfig --enableldap --enableldapauth --ldapserver=192.168.107.177 --ldapbasedn="dc=massclouds,dc=com" --enablemkhomedir --update

     重启客户端服务:

    systemctl restart  nslcd

     到此我们就在客户端机器上配置完了,也就是说现在我们就可以在LDAP server上集中管理这台客户端机器上的账号了。

    验证:

    [root@localhost ~]# getent passwd user01
    user01:*:836031732:500:user01:/home/user01:/bin/bash

     在这台客户端中,的确是不存在user01这个用户的。

     当我们使用user01 ssh登录客户端机器时可能会出现无法创建家目录的情况,关闭selinux就可以。

    搭建LDAP web 控制台 phpLDAPadmin

    phpLDAPadmin是使用php实现的一个管理OpenLDAP的web程序,我们将它部署在Apache Web Server(httpd)上,关于如何配置httpd就不再赘述了。

    安装php环境:

    yum -y install php php-mbstring php-pear php-ldap 

    下载phpldapadmin的安装文件,解压缩到/var/www/html目录中

    wget https://nchc.dl.sourceforge.net/project/phpldapadmin/phpldapadmin-php5/1.2.3/phpldapadmin-1.2.3.zip
    unzip phpldapadmin-1.2.3.zip
    mv phpldapadmin-1.2.3 phpldapadmin
    

     得到phpLDAPadmin的部署文件后,我们还要去配置需要访问的LDAP 服务器信息。

     把/var/www/html/phpldapadmin/config/config.php.example 文件重命名为 /var/www/html/phpldapadmin/config/config.php, 然后在300行左右,把注释去掉,并修改如下:

    293 $servers->setValue('server','host','192.168.107.177');
    294 
    295 /* The port your LDAP server listens on (no quotes). 389 is standard. */
    296 $servers->setValue('server','port',389);
    297 
    298 /* Array of base DNs of your LDAP server. Leave this blank to have phpLDAPadmin
    299    auto-detect it for you. */
    300 $servers->setValue('server','base',array('dc=massclouds,dc=com')); 
    
    

     之后重启httpd就可以了。在登录的时候,我遇到了无法验证用户的问题,同样是关闭seLinux后就好了。

    然后我们访问http://你的ip或域名/phpldapadmin/index.php 就可以访问了。点击左侧的登录按钮登录即可,登录DN是LDAP服务器上管理员的DN,密码就是管理员密码。 登录进去以后,我们就可以对整棵目录信息树(DIT)进行操作了。

    使用JLDAP 访问LDAP

    JLDAP是一个java实现的访问LDAP的第三方工具。 下面的大多数代码都直接来自 jldap实现Java对LDAP的基本操作 这篇文章,除此之外最主要的是有一个和 slappasswd 功能相同的计算OpenLDAP密码的java实现。

     新增节点:

    package com.massclouds.test;
    
    import java.io.UnsupportedEncodingException;
    import java.nio.charset.Charset;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    
    import org.apache.commons.codec.binary.Base64;
    
    import com.novell.ldap.LDAPAttribute;
    import com.novell.ldap.LDAPAttributeSet;
    import com.novell.ldap.LDAPConnection;
    import com.novell.ldap.LDAPEntry;
    import com.novell.ldap.LDAPException;
    
    public class LDAPAddEntry {
        /**
         * Openldap 产生SSHA密码的算法
         * 效果等同于 slappasswd -h {ssha} -s password
         * @param password
         * @return
         * @throws NoSuchAlgorithmException
         * @throws UnsupportedEncodingException 
         */
        public static String generateSSHAPwd(String password)
                throws NoSuchAlgorithmException, UnsupportedEncodingException {
            final int SALT_LENGTH = 4;
            SecureRandom secureRandom = new SecureRandom();
            byte[] salt = new byte[SALT_LENGTH];
            secureRandom.nextBytes(salt);
    
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(password.getBytes("utf-8"));
            crypt.update(salt);
            byte[] hash = crypt.digest();
    
            byte[] hashPlusSalt = new byte[hash.length + salt.length];
            System.arraycopy(hash, 0, hashPlusSalt, 0, hash.length);
            System.arraycopy(salt, 0, hashPlusSalt, hash.length, salt.length);
            
            return new StringBuilder().append("{SSHA}")
                    .append(new String(Base64.encodeBase64(hashPlusSalt), Charset.forName("utf-8")))
                    .toString();
        }
        
        public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    
            String ldapHost = "192.168.107.177"; //ldap服务端地址
            String loginDN = "cn=ldapadm,dc=massclouds,dc=com"; //ldap管理员DN
            String password = "secret"; //ldap管理员密码
            String containerName = "dc=massclouds,dc=com"; //目录信息树(DIT)的根节点
    
            int ldapPort = LDAPConnection.DEFAULT_PORT;
            int ldapVersion = LDAPConnection.LDAP_V3;
            LDAPConnection lc = new LDAPConnection();
            LDAPAttributeSet attributeSet = new LDAPAttributeSet();
    
            attributeSet.add(new LDAPAttribute("objectClass", new String[]{"inetOrgPerson",  "posixAccount", "top"}));
            
            attributeSet.add(new LDAPAttribute("uid", "zhangsan")); //uid 是登录系统的用户名
            attributeSet.add(new LDAPAttribute("sn", "zhangsan")); 
            attributeSet.add(new LDAPAttribute("cn", "zhangsan")); 
            attributeSet.add(new LDAPAttribute("uidNumber", "10000"));  
    
            
            attributeSet.add(new LDAPAttribute("loginShell", "/bin/bash"));
            attributeSet.add(new LDAPAttribute("homeDirectory", "/home/zhangsan")); 
            attributeSet.add(new LDAPAttribute("userPassword", generateSSHAPwd("111111")));
            attributeSet.add(new LDAPAttribute("gidNumber", "500"));
            
            String dn = "cn=cn,ou=People,dc=massclouds,dc=com";
            LDAPEntry newEntry = new LDAPEntry(dn, attributeSet);
            try {
                lc.connect(ldapHost, ldapPort);
                lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
                System.out.println("login ldap server successfully.");
                lc.add(newEntry);
                
                
                System.out.println("Added object: " + dn + " successfully.");
            } catch (LDAPException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                System.out.println("Error: " + e.toString());
            } finally {
                try {
                    if (lc.isConnected()) {
                        lc.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

     删除节点:

    package com.massclouds.test;
    
    import java.io.UnsupportedEncodingException;
    
    import com.novell.ldap.LDAPConnection;
    import com.novell.ldap.LDAPException;
    
    public class LDAPDeleteEntry {
    
        public static void main(String[] args) {
    
            String ldapHost = "192.168.107.177";
            String loginDN = "cn=ldapadm,dc=massclouds,dc=com";
            String password = "secret";
            //要删除节点的DN
            String deleteDN = "cn=cheng zhang,ou=People,dc=massclouds,dc=com";
    
            int ldapPort = LDAPConnection.DEFAULT_PORT;
            int ldapVersion = LDAPConnection.LDAP_V3;
            LDAPConnection lc = new LDAPConnection();
            try {
                lc.connect(ldapHost, ldapPort);
                lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
    
                lc.delete(deleteDN);
                System.out.println(" delete Entry: " + deleteDN + " success.");
                lc.disconnect();
            } catch (LDAPException e) {
                if (e.getResultCode() == LDAPException.NO_SUCH_OBJECT) {
                    System.err.println("Error: No such object");
                } else if (e.getResultCode() == LDAPException.INSUFFICIENT_ACCESS_RIGHTS) {
                    System.err.println("Error: Insufficient rights");
                } else {
                    System.err.println("Error: " + e.toString());
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println("Error: " + e.toString());
            } finally {
                try {
                    if (lc.isConnected()) {
                        lc.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
        }
    
    }

    修改属性( 包括新增、删除和替换属性)

    package com.massclouds.test;
    
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.util.ArrayList;
    import java.util.Base64;
    import java.util.List;
    
    import com.novell.ldap.LDAPAttribute;
    import com.novell.ldap.LDAPConnection;
    import com.novell.ldap.LDAPException;
    import com.novell.ldap.LDAPModification;
    
    public class LDAPModifyAttrs {
        public static String generateSSHAPwd(byte[] password)
                throws NoSuchAlgorithmException {
            final int SALT_LENGTH = 4;
            SecureRandom secureRandom = new SecureRandom();
            byte[] salt = new byte[SALT_LENGTH];
            secureRandom.nextBytes(salt);
    
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(password);
            crypt.update(salt);
            byte[] hash = crypt.digest();
    
            byte[] hashPlusSalt = new byte[hash.length + salt.length];
            System.arraycopy(hash, 0, hashPlusSalt, 0, hash.length);
            System.arraycopy(salt, 0, hashPlusSalt, hash.length, salt.length);
            
            return new StringBuilder().append("{SSHA}")
                    .append(Base64.getEncoder().encodeToString(hashPlusSalt))
                    .toString();
        }
        
        public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    
            String ldapHost = "192.168.107.177";
            String loginDN = "cn=ldapadm,dc=massclouds,dc=com";
            String password = "admin==1";
            String modifyDN = "cn=weiying,ou=People,dc=massclouds,dc=com";
    
            int ldapPort = LDAPConnection.DEFAULT_PORT;
            int ldapVersion = LDAPConnection.LDAP_V3;
            LDAPConnection lc = new LDAPConnection();
    
            List<LDAPModification> modList = new ArrayList<LDAPModification>();
    
            LDAPAttribute attribute = new LDAPAttribute("userPassword", generateSSHAPwd("11111".getBytes("utf-8")));
            //这里除了REPLACE还可以ADD,DELETE,表示新增和删除节点
            modList.add(new LDAPModification(LDAPModification.REPLACE, attribute));
    
            LDAPModification[] mods = new LDAPModification[modList.size()];
            mods = (LDAPModification[]) modList.toArray(mods);
    
            try {
                lc.connect(ldapHost, ldapPort);
                lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
                lc.modify(modifyDN, mods);
                System.out
                        .println("LDAPAttribute add、replace、delete all successful.");
            } catch (LDAPException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                System.out.println("Error: " + e.toString());
            } finally {
                try {
                    if (lc.isConnected()) {
                        lc.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
        }
    
    }

     查询节点:

    package com.massclouds.test;
    
    
    import java.io.UnsupportedEncodingException;
    import java.util.Enumeration;
    import java.util.Iterator;
    
    import com.novell.ldap.LDAPAttribute;
    import com.novell.ldap.LDAPAttributeSet;
    import com.novell.ldap.LDAPConnection;
    import com.novell.ldap.LDAPEntry;
    import com.novell.ldap.LDAPException;
    import com.novell.ldap.LDAPSearchResults;
    import com.novell.ldap.util.Base64;
    
    public class QueryTest {
        public static void main(String[] args) {
    
            String ldapHost = "192.168.107.177";
            String loginDN = "cn=ldapadm,dc=massclouds,dc=com";
            String password = "secret";
            String searchBase = "dc=massclouds,dc=com";
            String searchFilter = "objectClass=*";
    
            int ldapPort = LDAPConnection.DEFAULT_PORT;
            // 查询范围
            int searchScope = LDAPConnection.SCOPE_SUB;
    
            LDAPConnection lc = new LDAPConnection();
            try {
                lc.connect(ldapHost, ldapPort);
                lc.bind(LDAPConnection.LDAP_V3, loginDN, password.getBytes("UTF8"));
                LDAPSearchResults searchResults = lc.search(searchBase,
                        searchScope, searchFilter, null, false);
    
                while (searchResults.hasMore()) {
                    LDAPEntry nextEntry = null;
                    try {
                        nextEntry = searchResults.next();
                    } catch (LDAPException e) {
                        System.out.println("Error: " + e.toString());
                        if (e.getResultCode() == LDAPException.LDAP_TIMEOUT
                                || e.getResultCode() == LDAPException.CONNECT_ERROR) {
                            break;
                        } else {
                            continue;
                        }
                    }
                    
                    System.out.println("DN =: " + nextEntry.getDN());
                    System.out.println("|---- Attributes list: ");
                    
                    LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
                    Iterator<LDAPAttribute> allAttributes = attributeSet.iterator();
                    while (allAttributes.hasNext()) {
                        LDAPAttribute attribute = allAttributes.next();
                        String attributeName = attribute.getName();
                        
                        Enumeration<String> allValues = attribute.getStringValues();
                        if (null == allValues) {
                            continue;
                        }
                        while (allValues.hasMoreElements()) {
                            String value = allValues.nextElement();
                            
                            if (!Base64.isLDIFSafe(value)) {
                                // base64 encode and then print out
                                value = Base64.encode(value.getBytes());
                            }
                            System.out.println("|---- ---- " + attributeName
                                    + " = " + value);
                        }
                    }
                }
    
            } catch (LDAPException e) {
                System.out.println("Error: " + e.toString());
            } catch (UnsupportedEncodingException e) {
                System.out.println("Error: " + e.toString());
            } finally {
                try {
                    if (lc.isConnected()) {
                        lc.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

     以上就是增删改查的基本操作。

  • 相关阅读:
    poj 3616 Milking Time
    poj 3176 Cow Bowling
    poj 2229 Sumsets
    poj 2385 Apple Catching
    poj 3280 Cheapest Palindrome
    hdu 1530 Maximum Clique
    hdu 1102 Constructing Roads
    codeforces 592B The Monster and the Squirrel
    CDOJ 1221 Ancient Go
    hdu 1151 Air Raid(二分图最小路径覆盖)
  • 原文地址:https://www.cnblogs.com/zh1164/p/6769137.html
Copyright © 2011-2022 走看看