设置Windows / AD密码,使其“永不过期”?

时间:2012-06-14 01:17:11

标签: c# directoryentry

这是我的代码:

using (DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName +    ",computer"))
{
   DirectoryEntry NewUser = AD.Children.Add(username, "user");
   string password = username + "123";
   NewUser.Invoke("SetPassword", new object[] { password });
   NewUser.CommitChanges();
   NewUser.Close();
   DirectoryEntry grp;
   grp = AD.Children.Find(groupname, "group");
   if (grp != null)
    {
      grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
    }
}

我想要做的是创建一个Windows用户并设置密码永不过期, 但我不知道该怎么做?

3 个答案:

答案 0 :(得分:5)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义计算机上下文并在本地服务器上轻松创建新用户:

// set up machine-level context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
{
    // create new user
    UserPrincipal newUser = new UserPrincipal(ctx);

    // set some properties
    newUser.SamAccountName = "Sam";
    newUser.DisplayName = "Sam Doe";

    // define new user to be enabled and password never expires
    newUser.Enabled = true;
    newUser.PasswordNeverExpires = true;

    // save new user
    newUser.Save();
}

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!

答案 1 :(得分:3)

* EDITED

对于域帐户:

int NON_EXPIRE_FLAG = 0x10000;
val = (int) NewUser.Properties["userAccountControl"].Value;
NewUser.Properties["userAccountControl"].Value = val | NON_EXPIRE_FLAG;
NewUser.CommitChanges();

对于本地帐户:

我相信你会使用“UserFlags”而不是userAccountControl

答案 2 :(得分:0)

这是我用来解决此问题的代码:
enter image description here

// Add new user to OU
var username = "testuser_01";
var userDn = "LDAP://yourdomain.local:389/OU=testou,cn=yourdomain,cn=local";
var ouUserEntry = new DirectoryEntry(userDn, "yourAdminUser", "yourAdminPassword", AuthenticationTypes.Secure);
var newUserEntry = ouUserEntry.Children.Add("CN="+ username, "user");
newUserEntry.Properties["sAMAccountName"].Value = username;
newUserEntry.Properties["userPrincipalName"].Value = username + "@abc.com";
newUserEntry.Properties["displayName"].Value = username;

// Commit before enable account
newUserEntry.CommitChanges();

// Set password
newUserEntry.Invoke("SetPassword", "yourUserPassword");

// Enable Account & Password never expired (NORMAL_ACCOUNT | DONT_EXPIRE_PASSWORD)
newUserEntry.Properties["userAccountControl"].Value = 66080; // integer value in image above
newUserEntry.CommitChanges();