java ldap增加用户
时间: 2023-07-11 19:22:13 浏览: 104
可以使用Java中的JNDI(Java Naming and Directory Interface)API来连接LDAP服务器,并执行添加用户的操作。以下是一个简单的Java代码示例:
```java
import javax.naming.*;
import javax.naming.directory.*;
public class LDAPAddUserExample {
public static void main(String[] args) {
// LDAP服务器信息
String ldapURL = "ldap://localhost:389";
String ldapUser = "cn=admin,dc=mydomain,dc=com";
String ldapPassword = "adminpassword";
// 用户信息
String username = "newuser";
String userPassword = "password";
String userFullName = "New User";
String userDescription = "A new user account";
try {
// 创建LDAP连接
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapURL);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapUser);
env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
DirContext ctx = new InitialDirContext(env);
// 创建用户对象
Attributes attrs = new BasicAttributes();
attrs.put("objectClass", "top");
attrs.put("objectClass", "person");
attrs.put("objectClass", "organizationalPerson");
attrs.put("objectClass", "inetOrgPerson");
attrs.put("uid", username);
attrs.put("cn", userFullName);
attrs.put("sn", username);
attrs.put("userPassword", userPassword);
attrs.put("description", userDescription);
// 添加用户
ctx.createSubcontext("uid=" + username + ",ou=users,dc=mydomain,dc=com", attrs);
// 关闭LDAP连接
ctx.close();
System.out.println("User added successfully!");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
```
需要替换代码中的LDAP服务器信息和用户信息为实际值,并确保LDAP服务器已启动并可用。此代码将在LDAP服务器的“ou=users,dc=mydomain,dc=com”组织单元中创建一个名为“newuser”的用户。
阅读全文