【问题标题】:C# ActiveDirectory - How do I add a local user account remotely from a domain-joined machine to a non-domain machineC# ActiveDirectory - 如何将本地用户帐户从加入域的计算机远程添加到非域计算机
【发布时间】:2010-12-15 20:59:19
【问题描述】:

我正在尝试在未加入域的计算机上添加本地用户帐户。我已经尝试了几乎所有我能想到的东西。我在同一个域中的机器上工作,但不在域外机器上。我可以 ping 和 TS 到此服务器,但似乎无法添加管理员。

是否可以使用 DirectoryEntry 来执行此操作?

这是我目前拥有的代码(为了便于阅读,稍作改动):

    private string AddLocalAdmin_NonDomain(string ComputerName)
    {
        StartImpersonation(); //Uses advapi32.dll->LogonUser()
        string ErrMsg = "";
        const int ADS_UF_DONT_EXPIRE_PASSWD = 0x10000;
        DirectoryEntry AD = new DirectoryEntry("WinNT://" + ComputerName + ",computer", ComputerName + "\\" + UserCredentials.Username, UserCredentials.Password);
        object n = AD.NativeObject;
        DirectoryEntry NewUser = AD.Children.Add(Username, "user");
        NewUser.Invoke("SetPassword", new object[] { Password });
        if (!PasswordExpires)
        {
            int val = ADS_UF_DONT_EXPIRE_PASSWD;
            NewUser.InvokeSet("userFlags", new object[] { val });
        }
        NewUser.CommitChanges();
        DirectoryEntry grp;
        grp = AD.Children.Find("Administrators", "group");
        if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); }
        EndImpersonation(); //Ends the impersonation
        return ErrMsg; //returns "Access Denied"
    }

【问题讨论】:

    标签: c# active-directory


    【解决方案1】:

    你可以使用

    System.DirectoryServices.AccountManagement
    

    为了实现这里是代码

    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);
    
    //Create New User
    UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, "Your UserName", "Your Password", true /*Enabled or not*/);
    
    oUserPrincipal.UserPrincipalName = "Your UserName";
    oUserPrincipal.GivenName = "Given Name";
    oUserPrincipal.Surname = "Surname";
    oUserPrincipal.Save();
    
    //Add User to Group
    GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Your Group Name");
    oGroupPrincipal.Members.Add(oUserPrincipal);
    oGroupPrincipal.Save();
    

    如需完整实现,请前往http://anyrest.wordpress.com/2010/06/28/active-directory-c/

    【讨论】:

    • 感谢您的回复。该方法比我的 ASDI 查询要好得多。不幸的是,这种方法适用于同一域中的机器,但不适用于未加入的机器。我尝试将凭据传递到 oPrincipalContext 以及使用 LogonUser 方法。有什么想法吗?
    • 对不起,我不能完全得到你的回应,你的意思是你只在没有域的情况下查询本地机器上的用户?
    • 对不起。让我澄清一下我想要做什么:我想使用这个应用程序从我的桌面 DESK1(在域 XDEV 上)远程添加一个管理员到 SERVER1(根本没有域)。我可以添加到我拥有管理员帐户的同一域上的任何计算机。我还可以模拟另一个帐户(即 TECHADMIN),该帐户是该计算机上的本地管理员。问题是当我需要从域机器上添加非域机器上的用户时。我不是真的 100% 确定它是可能的。我可以使用 psexec,但我希望直接使用 AD,因为它有点干净。这有意义吗?
    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2017-09-20
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多