嗨,我正在尝试从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
参数。但是,它不会减少查询数量,只会减少返回的数据量。
posixAccount
和posixGroup
对象(除非目录服务器执行此操作,但我怀疑会这样做),否则它将变得不一致。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句