您好,我正在尝试从 LDAP 中获取所有 posixGroup 以及该组中的用户。下面的代码是我到目前为止所做的,它返回我所有的组,但我不确定如何获取这些组的用户。请指导我这种方法好吗?或者我应该先获取用户,然后根据 GID 获取组名?
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
以用户名作为值(在 RFC 2307 中定义)。还有其他可能的属性(成员、唯一成员)和值 (DN),因此请检查您的目录使用的内容。
因此,为了加载组中的所有用户,您必须:
- 查询该组,例如使用此过滤器
(&(objectClass=posixGroup)(cn=<group name>))
- 迭代
memberUid
的所有值在组中,对于每个: - 使用
(&(objectClass=posixAccount)(uid=<memberUid>))
查询用户对象 - 然后您可以访问用户属性,例如
uidNumber
.
这不是一种非常有效的方法,因为它会生成大量小查询,但据我所知,LDAP 无法将组条目与其在单个结果中引用的用户条目连接起来(与此不同) SQL)。
您可以通过将结果限制为您实际需要的属性来对其进行一些优化:gidNumber
用于组查询和 uidNumber
供用户查询。使用 SearchControls.setReturningAttributes()
或 DirContext.search()
的版本这需要 attributesToReturn
争论。但它并没有减少查询数量,只是减少了返回的数据量。
有关 LDAP 使用的一些更一般的说明
- 如果您的查询有大量结果(例如“所有用户”),您可能会达到目录的结果大小限制(通常为 5000 个),并且只能获得部分结果。
- 修改群组成员信息时,您必须更新
posixAccount
和posixGroup
对象(除非你的目录服务器这样做,但我怀疑它会这样做),否则它会变得不一致。
关于java - 从 LDAP 获取组和用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25356874/