6

在 Vista 开发机器上,我成功使用此代码更改用户“管理员”密码:

directoryEntry.Invoke("SetPassword", "new");

当我将它移到我的 Server 2008 开发机器上时,该代码不起作用,我被迫使用以下代码:

directoryEntry.Invoke("ChangePassword", new object[] { "old", "new" });

我的问题是,为什么?

对于这两种情况,我都这样创建了我的 DirectoryEntry 对象:

DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username));

谢谢!8)

如果你们觉得它有帮助,这里是实际的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.DirectoryServices;
using System.Security.Principal;

namespace AccountMod
{
   class Program
   {
        static void Main()
        {
           Console.WriteLine("Attempting reset...\n");
           try
           {
               String machineNameAndUser =    WindowsIdentity.GetCurrent().Name.ToString();
               String machineName =    WindowsIdentity.GetCurrent().Name.ToString().Substring(0,    machineNameAndUser.IndexOf('\\'));
            Console.WriteLine("Computer's name: " + machineName);
            ResetPassword(machineName, "Administrator", "new");
            //ChangePassword("Administrator", "current", "new");                      Console.WriteLine("Finished...");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.InnerException);
            }
            Console.ReadKey();

        }

        public static void ResetPassword(string computerName, string username, string newPassword)
        {
            DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username));
            directoryEntry.Invoke("SetPassword", newPassword);
            //directoryEntry.Invoke("ChangePassword", new object[] { "current", "new" });
        }
    }
}
4

2 回答 2

5

您是(或者您可以升级到).NET 3.5 吗?用户、组、计算机的 AD 集成在 .NET 3.5 中得到了极大改进 - 请查看 MSDN 文章在 .NET Framework 3.5 中管理目录安全主体以了解详细信息。

在您的情况下,您可以执行以下操作:

// establish context for local machine
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);

// find the "Administrator" account
UserPrincipal admin = UserPrincipal.FindByIdentity(ctx, "Administrator");

// set the password to a new value
admin.SetPassword("new-top-secret-password");
admin.Save();

你就完成了!提供WinNT:者的功能非常有限,应尽可能避免。

于 2010-04-11T06:51:40.253 回答
0

检查您要为其设置密码的用户属性,如果

用户不能更改密码

检查属性,然后您无法通过使用directoryEntry.Invoke("SetPassword", "new");创建 DirectoryEntry 对象时使用管理员凭据设置密码或取消选中“用户无法更改密码”属性

于 2013-02-01T07:10:02.857 回答