创建本地用户帐户 C# 和 .NET 2.0

发布于 2024-07-10 06:36:06 字数 129 浏览 3 评论 0原文

如何使用 .NET 2.0 和 c# 创建本地用户帐户,并且能够将“密码永不过期”设置为永不。

我尝试使用“Net.exe”使用 Process.Start 并传递其参数,但似乎“网络用户”无法将“密码永不过期”设置为永不。

How can I create a local user account using .NET 2.0 and c# and also be able to set the "Password never expires" to never.

I have tried using "Net.exe" using Process.Start and passing its parameters but it seems that the "net user" is unable to set the "Password never expires" to never.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏了南城 2024-07-17 06:36:06

阅读这篇优秀的 CodeProject 文章

Howto:(几乎)通过 C# 实现 Active Directory 中的所有内容< /strong>

有一个“创建用户帐户”和“处理用户密码”部分。

更新:

要调整本地帐户的代码,请将相应的行替换为以下内容:

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + 
    Environment.MachineName);
DirectoryEntry newUser = localMachine.Children.Add("localuser", "user");

这里开始域帐户的原始代码片段:

public string CreateUserAccount(string ldapPath, string userName, 
    string userPassword)
{
    string oGUID = string.Empty;
    try
    {          
        string connectionPrefix = "LDAP://" + ldapPath;
        DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
        DirectoryEntry newUser = dirEntry.Children.Add
            ("CN=" + userName, "user");
        newUser.Properties["samAccountName"].Value = userName;

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

        newUser.CommitChanges();
        oGUID = newUser.Guid.ToString();

        newUser.Invoke("SetPassword", new object[] { userPassword });
        newUser.CommitChanges();

        dirEntry.Close();
        newUser.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingwith --> E.Message.ToString();    
    }
    return oGUID;
}

有一些细节需要理解
在处理用户密码时
密码周围的边界,例如
强迫用户改变他们的
下次登录时输入密码,拒绝
用户有权自行更改
密码,将密码设置为从不
过期,到什么时候过期,以及这些
任务可以使用完成
UserAccountControl 标志是
诉讼中证明
部分。

请参考这个很棒的
MSDN 文章:管理用户密码
示例和文档
关于这些功能。

CONST                          HEX
------------------------------------------
SCRIPT                         0x0001
ACCOUNTDISABLE                 0x0002
HOMEDIR_REQUIRED               0x0008
LOCKOUT                        0x0010
PASSWD_NOTREQD                 0x0020
PASSWD_CANT_CHANGE             0x0040
ENCRYPTED_TEXT_PWD_ALLOWED     0x0080
TEMP_DUPLICATE_ACCOUNT         0x0100
NORMAL_ACCOUNT                 0x0200
INTERDOMAIN_TRUST_ACCOUNT      0x0800
WORKSTATION_TRUST_ACCOUNT      0x1000
SERVER_TRUST_ACCOUNT           0x2000
DONT_EXPIRE_PASSWORD           0x10000
MNS_LOGON_ACCOUNT              0x20000
SMARTCARD_REQUIRED             0x40000
TRUSTED_FOR_DELEGATION         0x80000
NOT_DELEGATED                  0x100000
USE_DES_KEY_ONLY               0x200000
DONT_REQ_PREAUTH               0x400000
PASSWORD_EXPIRED               0x800000
TRUSTED_TO_AUTH_FOR_DELEGATION 0x1000000

Read this excellent CodeProject article

Howto: (Almost) Everything In Active Directory via C#

There is a section "Create User Account" and "Dealing with User Passwords".

UPDATE:

To adapt the code for local accounts replace the respective lines with these:

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + 
    Environment.MachineName);
DirectoryEntry newUser = localMachine.Children.Add("localuser", "user");

Here starts the original code snippet for domain accounts:

public string CreateUserAccount(string ldapPath, string userName, 
    string userPassword)
{
    string oGUID = string.Empty;
    try
    {          
        string connectionPrefix = "LDAP://" + ldapPath;
        DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
        DirectoryEntry newUser = dirEntry.Children.Add
            ("CN=" + userName, "user");
        newUser.Properties["samAccountName"].Value = userName;

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

        newUser.CommitChanges();
        oGUID = newUser.Guid.ToString();

        newUser.Invoke("SetPassword", new object[] { userPassword });
        newUser.CommitChanges();

        dirEntry.Close();
        newUser.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingwith --> E.Message.ToString();    
    }
    return oGUID;
}

There are some specifics to understand
when dealing with user passwords and
boundaries around passwords such as
forcing a user to change their
password on the next logon, denying
the user the right to change their own
passwords, setting passwords to never
expire, to when to expire, and these
tasks can be accomplished using
UserAccountControl flags that are
demonstrated in the proceeding
sections.

Please refer to this great
MSDN article: Managing User Passwords
for examples and documentation
regarding these features.

CONST                          HEX
------------------------------------------
SCRIPT                         0x0001
ACCOUNTDISABLE                 0x0002
HOMEDIR_REQUIRED               0x0008
LOCKOUT                        0x0010
PASSWD_NOTREQD                 0x0020
PASSWD_CANT_CHANGE             0x0040
ENCRYPTED_TEXT_PWD_ALLOWED     0x0080
TEMP_DUPLICATE_ACCOUNT         0x0100
NORMAL_ACCOUNT                 0x0200
INTERDOMAIN_TRUST_ACCOUNT      0x0800
WORKSTATION_TRUST_ACCOUNT      0x1000
SERVER_TRUST_ACCOUNT           0x2000
DONT_EXPIRE_PASSWORD           0x10000
MNS_LOGON_ACCOUNT              0x20000
SMARTCARD_REQUIRED             0x40000
TRUSTED_FOR_DELEGATION         0x80000
NOT_DELEGATED                  0x100000
USE_DES_KEY_ONLY               0x200000
DONT_REQ_PREAUTH               0x400000
PASSWORD_EXPIRED               0x800000
TRUSTED_TO_AUTH_FOR_DELEGATION 0x1000000
帅气尐潴 2024-07-17 06:36:06

此代码将创建一个本地帐户,并设置密码永不过期选项:

        using System.DirectoryServices;

        DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost");
        DirectoryEntries entries = hostMachineDirectory.Children;
        bool userExists = false;
        foreach (DirectoryEntry each in entries)
        {
            userExists = each.Name.Equals("NewUser",  
            StringComparison.CurrentCultureIgnoreCase);
            if (systemtestUserExists)
                break;
        }

        if (false == userExists)
        {
            DirectoryEntry obUser = entries.Add("NewUser", "User");
            obUser.Properties["FullName"].Add("Local user");
            obUser.Invoke("SetPassword", "abcdefg12345@");
            obUser.Invoke("Put", new object[] {"UserFlags", 0x10000});
            obUser.CommitChanges();
        }

0x10000 标志表示密码永不过期。

我花了很长时间弄清楚如何创建一个密码设置不过期的本地用户帐户。 似乎当您尝试使用:

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

来自活动目录的权限时就会发挥作用。 如果您具有活动目录权限,则一切正常。 如果不这样做,那么获取 userAccountControl 属性将始终导致空值。 尝试设置 userAccountControl 将导致异常“在缓存中找不到目录属性”。

然而,经过多次搜寻,我发现另一个属性“UserFlags”需要使用 Invoke 设置。 您可以使用它在本地帐户上设置标志。 我已经尝试过这段代码,它可以在 Windows Server 2008 上运行。

希望这会有所帮助

This code will create a local account with the password never expires option set:

        using System.DirectoryServices;

        DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost");
        DirectoryEntries entries = hostMachineDirectory.Children;
        bool userExists = false;
        foreach (DirectoryEntry each in entries)
        {
            userExists = each.Name.Equals("NewUser",  
            StringComparison.CurrentCultureIgnoreCase);
            if (systemtestUserExists)
                break;
        }

        if (false == userExists)
        {
            DirectoryEntry obUser = entries.Add("NewUser", "User");
            obUser.Properties["FullName"].Add("Local user");
            obUser.Invoke("SetPassword", "abcdefg12345@");
            obUser.Invoke("Put", new object[] {"UserFlags", 0x10000});
            obUser.CommitChanges();
        }

The 0x10000 flag means PasswordNeverExpires.

I spent a long time figuring out how to create a local user account with the password set not to expire. It seems that when you try to use:

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

permissions from active directory come into play. If you have active directory permissions everything works fine. If you don't then getting the userAccountControl property will always result in a null value. Trying to set userAccountControl will result in an exception "The directory property cannot be found in the cache".

However after much hunting around I found another property "UserFlags" that needs to be set using Invoke. You can use this to set the flag on a local account. I've tried this code and it worked on windows server 2008.

Hope this helps

空宴 2024-07-17 06:36:06

使用系统目录服务;

    DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost");
    DirectoryEntries entries = hostMachineDirectory.Children;
    bool userExists = false;
    foreach (DirectoryEntry each in entries)
    {
        userExists = each.Name.Equals("NewUser",  
        StringComparison.CurrentCultureIgnoreCase);
        if (systemtestUserExists)
            break;
    }

    if (false == userExists)
    {
        DirectoryEntry obUser = entries.Add("NewUser", "User");
        obUser.Properties["FullName"].Add("Local user");
        obUser.Invoke("SetPassword", "abcdefg12345@");
        obUser.Invoke("Put", new object[] {"UserFlags", 0x10000});
        obUser.CommitChanges();

using System.DirectoryServices;

    DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost");
    DirectoryEntries entries = hostMachineDirectory.Children;
    bool userExists = false;
    foreach (DirectoryEntry each in entries)
    {
        userExists = each.Name.Equals("NewUser",  
        StringComparison.CurrentCultureIgnoreCase);
        if (systemtestUserExists)
            break;
    }

    if (false == userExists)
    {
        DirectoryEntry obUser = entries.Add("NewUser", "User");
        obUser.Properties["FullName"].Add("Local user");
        obUser.Invoke("SetPassword", "abcdefg12345@");
        obUser.Invoke("Put", new object[] {"UserFlags", 0x10000});
        obUser.CommitChanges();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文