【问题标题】:How to create new user account without password如何创建没有密码的新用户帐户
【发布时间】:2018-05-30 10:00:20
【问题描述】:

我想以编程方式将新的本地用户添加到计算机。我找到了代码here。 但我希望用户无需密码即可登录。我看到有一个选项 UserPrincipal.PasswordNotRequired=true 但如果我不使用 SetPassword() 它会抛出一个异常:

密码不符合密码政策要求...

是否可以创建一个没有密码的新用户?

编辑:当前代码,成功添加新用户,但我必须提供一些密码。它是来自提供的链接的完整副本:

PrincipalContext oPrincipalContext = GetPrincipalContext();

UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext);
oUserPrincipal.Name = sUserName;
oUserPrincipal.SetPassword(sPassword);
oUserPrincipal.DisplayName = windowsUsername.Text;
oUserPrincipal.PasswordNeverExpires = true;
oUserPrincipal.PasswordNotRequired = true;
oUserPrincipal.Save();

GroupPrincipal usersGroup = GroupPrincipal.FindByIdentity(oPrincipalContext, "Users");
usersGroup.Members.Add(oUserPrincipal);
usersGroup.Save();

【问题讨论】:

  • 您可以设置组账号,使远程PC上的用户密码和本地PC上的用户密码相同,远程连接时无需密码。您需要在本地和远程 PC 上设置相同的组帐户。还必须将用户添加到组中。
  • 你能展示一个更完整的代码版本吗
  • 嗨,谢谢。情况是,我没有任何远程 PC。我只想运行一个程序来创建没有密码的新用户帐户。我需要它来自动配置一些计算机。
  • 您尝试添加用户的计算机是否也是域的一部分?
  • 我是这么认为的,因为上下文(域)是PrincipalContext(ContextType.Machine);所以基本上是本地机器。

标签: c# .net windows userprincipal


【解决方案1】:

您的代码无法正常工作有两个潜在原因。

  1. 您没有以管理员身份运行
  2. 您的计算机位于一个域中,该域的组策略阻止了您想要执行的操作。

下面的代码已经在我的机器上测试过并且可以运行。

void Main()
{
    PrincipalContext oPrincipalContext = GetPrincipalContext();

    UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext);
    oUserPrincipal.Name = "TestUser";
    oUserPrincipal.SetPassword("");
    oUserPrincipal.DisplayName = "TestUser";
    oUserPrincipal.PasswordNeverExpires = true;
    oUserPrincipal.PasswordNotRequired = true;
    oUserPrincipal.Save();

    GroupPrincipal usersGroup = GroupPrincipal.FindByIdentity(oPrincipalContext, "Users");
    usersGroup.Members.Add(oUserPrincipal);
    usersGroup.Save();
}

PrincipalContext GetPrincipalContext()
{
    var dc = new PrincipalContext(ContextType.Machine);
    return dc;
}

你可以尝试的东西, 1. 在不在您域中的机器上试用。 2. 在没有应用任何组策略的机器上试一试。 3. 在您遇到问题的机器上以管理员身份运行您的应用

【讨论】:

  • 原因是我在一台有域组策略的电脑上开发的。当我尝试在目标 PC 上运行可执行文件时,即使没有密码也能正常工作 - 正如预期的那样。非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
相关资源
最近更新 更多