java ad 添加用户组_在AD中创建用户并将用户加入到AD组中
时间: 2024-05-07 21:23:32 浏览: 125
在AD中创建用户并将用户加入到AD组中,可以通过Java的LDAP API实现。下面是一个示例代码:
```java
import javax.naming.*;
import javax.naming.directory.*;
public class AddUserToGroup {
public static void main(String[] args) {
String userName = "newuser";
String userPassword = "password";
String groupName = "group1";
try {
// Set up the environment for creating the initial context
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "admin");
env.put(Context.SECURITY_CREDENTIALS, "password");
// Create the initial context
DirContext ctx = new InitialDirContext(env);
// Create attributes for the user
Attributes userAttrs = new BasicAttributes();
userAttrs.put("objectClass", "person");
userAttrs.put("sAMAccountName", userName);
userAttrs.put("userPassword", userPassword);
// Create the user
ctx.createSubcontext("cn=" + userName + ",ou=users,dc=mydomain,dc=com", userAttrs);
// Get the group
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = ctx.search("ou=groups,dc=mydomain,dc=com",
"cn=" + groupName, ctls);
SearchResult result = results.next();
// Add the user to the group
Attribute member = new BasicAttribute("member", "cn=" + userName + ",ou=users,dc=mydomain,dc=com");
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, member);
ctx.modifyAttributes(result.getName(), mods);
// Close the context
ctx.close();
System.out.println("User " + userName + " added to group " + groupName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们通过LDAP连接到AD,并创建了一个名为“newuser”的用户。然后,我们搜索名为“group1”的组,并将用户添加到该组中。请注意,我们需要在“member”属性中指定用户的完整DN,才能将其添加到组中。最后,我们关闭了LDAP连接。
请根据你的实际情况修改代码中的参数,例如LDAP服务器地址、管理员账号密码、用户和组名等。
阅读全文