fbpx

Java Naming and Directory Interface (JNDI) API - NIS連線實作教學

Sun JNDI 官方網站

http://java.sun.com/products/jndi/

nis.jar為NIX所需Lib

範例程式如下:

import java.util.Properties;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;

public class TestJndi {

    public static void main(String[] args) {
        Properties env = new Properties();
        env.put(DirContext.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.nis.NISCtxFactory");
        env.put(DirContext.PROVIDER_URL, "nis://127.0.0.1/nisdomainname");
        try {
            InitialDirContext ctx = new InitialDirContext(env);
            NamingEnumeration list = ctx.list("system/passwd");
            while (list.hasMoreElements()) {
                String username = list.nextElement().getName();
                Attributes atts = ctx
                        .getAttributes("system/passwd/" + username);
                System.out.println(atts.get("uidNumber").get());
                System.out.println(atts.get("gidNumber").get());
                System.out.println(atts.get("cn").get());
                System.out.println(atts.get("homeDirectory").get());
                System.out.println(atts.get("userPassword").get());
                System.out.println(atts.get("nisMapEntry").get());
            }
        } catch (NamingException ex) {
            ex.printStackTrace();
        }

    }

}

 

發佈留言