Set Windows/AD password so that it “never expires”?

前端 未结 3 535
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 05:39

Here is my code:

using (DirectoryEntry AD = new DirectoryEntry(\"WinNT://\" + Environment.MachineName +    \",computer\"))
{
   DirectoryEntry NewUser = AD.C         


        
相关标签:
3条回答
  • 2020-12-21 06:13

    *EDITED

    For domain accounts:

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

    For local accounts:

    I believe you'd use "UserFlags" instead of userAccountControl

    0 讨论(0)
  • 2020-12-21 06:16

    If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

    • Managing Directory Security Principals in the .NET Framework 3.5
    • MSDN docs on System.DirectoryServices.AccountManagement

    Basically, you can define a machine context and easily create new users on your local server:

    // 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();
    }
    

    The new S.DS.AM makes it really easy to play around with users and groups in AD!

    0 讨论(0)
  • 2020-12-21 06:36

    This is my code to resolve this issue:

    // 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();
    
    0 讨论(0)
提交回复
热议问题