package demo;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class ADOperTest {

    public void GetADInfo(boolean isUser) {
        String host = "192.168.1.188"; // AD服务器
        String port = "389"; // 端口
        String url = new String("ldap://" + host + ":" + port);
        Hashtable HashEnv = new Hashtable();
        String adminName = "administrator@gzrb.local"; // 注意用户名的写法:domain\User
        String adminPassword = "2015"; // 密码
        HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
        HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User
        HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password
        HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
        HashEnv.put(Context.PROVIDER_URL, url);
        try {
            LdapContext ctx = new InitialLdapContext(HashEnv, null);
            // 域节点
            String searchBase = "OU=广州日报集团,DC=gzrb,DC=local";
            // LDAP搜索过滤器类
            String searchFilter = isUser ? "(&(objectClass=user))"
                    : "(&(objectClass=organizationalUnit))";
            // 搜索控制器
            SearchControls searchCtls = new SearchControls(); // Create the
            // 创建搜索控制器
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Specify
            // 定制返回属性
            String[] returnedAtts = null;
            if (isUser) {
                returnedAtts = new String[] { "sAMAccountName",
                        "distinguishedName", "name" };
            } else {
                returnedAtts = new String[] { "ou", "distinguishedName", "name" };
            }
            searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
            // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
            NamingEnumeration answer = ctx.search(searchBase, searchFilter,
                    searchCtls);// Search for objects using the filter
            while (answer.hasMoreElements()) {// 遍历结果集
                SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN
                String dn = sr.getAttributes().get("distinguishedName").get()
                        .toString();
                System.out.println(dn);
                Attributes Attrs = sr.getAttributes();// 得到符合条件的属性集
                if (Attrs != null) {
                    try {
                        for (NamingEnumeration ne = Attrs.getAll(); ne
                                .hasMore();) {
                            Attribute Attr = (Attribute) ne.next();// 得到下一个属性
                            System.out.print(" 属性名:" + Attr.getID().toString());
                            // 读取属性值
                            for (NamingEnumeration e = Attr.getAll(); e
                                    .hasMore();) {
                                String val = e.next().toString();
                                System.out.println("   属性值:" + val);
                            }

                        }
                    } catch (NamingException e) {
                        System.err.println("Throw Exception : " + e);
                    }
                }// if
            }
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
            System.err.println("Throw Exception : " + e);
        }

    }

    public void login() {

        String userName = "administrator@hotent.local"; // 用户名称
        String password = "2015"; // 密码
        String host = "192.168.1.188"; // AD服务器
        String port = "389"; // 端口
        String domain = "@hotent.local"; // 邮箱的后缀名
        String url = new String("ldap://" + host + ":" + port);
        String user = userName.indexOf(domain) > 0 ? userName : userName
                + domain;
        Hashtable env = new Hashtable();

        LdapContext ctx = null;
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, user); // 不带邮箱后缀名的话,会报错,具体原因还未探究。高手可以解释分享。
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url);
        try {
            ctx = new InitialLdapContext(env, null);
            ctx.close();
            System.out.println("验证成功!");
        } catch (NamingException err) {
            err.printStackTrace();
            System.out.println("验证失败!");
        }
    }

    public static void main(String args[]) {
        // 实例化
        ADOperTest ad = new ADOperTest();
        ad.GetADInfo(true);
//        System.out.println("---------组织---------");
//        ad.GetADInfo(false);
        ad.login();
    }
}
这样遍历系统中的用户,组织,和登录。
posted on 2015-05-31 18:48  自由港  阅读(620)  评论(0编辑  收藏  举报