Java 从LDAP获取组和用户
您好,我正在尝试从LDAP和该组中的用户获取所有posixGroup。下面的代码是我到目前为止所做的,它返回我所有的组,但我不知道如何获得这些组的用户。请指导我这个方法好吗?或者我应该先获取用户,然后根据GID获取组名吗Java 从LDAP获取组和用户,java,ldap,Java,Ldap,您好,我正在尝试从LDAP和该组中的用户获取所有posixGroup。下面的代码是我到目前为止所做的,它返回我所有的组,但我不知道如何获得这些组的用户。请指导我这个方法好吗?或者我应该先获取用户,然后根据GID获取组名吗 public static void main(String[] args) { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.
public static void main(String[] args) {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,"ldap://192.168.*.*:389");
env.put(Context.URL_PKG_PREFIXES, "com.sun.jndi.url");
env.put(Context.REFERRAL, "ignore");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=manager,dc=*,dc=*");
env.put(Context.SECURITY_CREDENTIALS, "****");
DirContext ctx;
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
throw new RuntimeException(e);
}
NamingEnumeration results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = ctx.search("ou=path,dc=*,dc=*", "(objectClass=posixGroup)",controls);
// Go through each item in list
while (results.hasMore()) {
SearchResult nc = (SearchResult)results.next();
Attributes att= nc.getAttributes();
System.out.println("Group Name "+ att.get("cn").get(0));
System.out.println("GID "+ att.get("GidNumber").get(0));
}
} catch (NameNotFoundException e) {
System.out.println("Error : "+e);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
System.out.println("Error : "+e);
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
System.out.println("Error : "+e);
}
}
}
}
查询组中的所有用户
这取决于目录中的组使用哪个属性来表示成员身份posixGroup
使用memberUid
,用户名作为值(在中定义)。还有其他可能的属性(member、uniquemember)和值(DN),所以请检查目录使用了什么
因此,为了从组中加载所有用户,您必须:
(&(objectClass=posixGroup)(cn=)
memberUid
的所有值,针对每个值:
(&(objectClass=posixAccount)(uid=))查询用户对象
uidNumber
gidNumber
用于组查询,而uidNumber
用于用户查询。使用具有attributesToReturn
参数的或其版本。但是,它并没有减少查询的数量,只是减少了返回的数据量
关于LDAP使用的一些更一般的说明
- 如果您的查询有大量结果(例如“所有用户”),您可能会达到目录的结果大小限制(通常为5000),并且只得到部分结果
- 在修改组成员信息时,必须同时更新
和posixAccount
对象(除非目录服务器这样做,但我怀疑它会这样做),否则它会变得不一致posixGroup