简体   繁体   English

将本地用户添加到本地管理员组

[英]Adding Local User to Local Admin Group

I am writing a C# program to be pushed out the labs I work in. The program is to create a local admin account(itadmin), set the password, set the password to never expire, and add the account to the local Administrators group.我正在编写一个 C# 程序来推送我工作的实验室。该程序是创建一个本地管理员帐户(itadmin),设置密码,将密码设置为永不过期,并将该帐户添加到本地管理员组。 The program creates the new user account and sets everything correctly but when it attempts to add it to the admin group I get a very nondescript exception.该程序创建了新的用户帐户并正确设置了所有内容,但是当它尝试将其添加到管理员组时,我得到了一个非常难以描述的异常。 Do I have the add to group correct in the first place?我首先添加到组是否正确? What am I missing?我错过了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace CreateITAdmin
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string userName = "itadmin";
                string userPassword = "password";

                Console.WriteLine("Building System Information");
                DirectoryEntry localMachine = new DirectoryEntry("WinNT://.,computer");
                DirectoryEntry newUser = localMachine.Children.Add(userName, "user");
                DirectoryEntry admGroup = new DirectoryEntry("WinNT://./Administrators,group");

                Console.WriteLine("Building User Information");
                newUser.Properties["FullName"].Value = "IT Administrative User";
                newUser.Invoke("Put", new object[] { "UserFlags", 0x10000 });

                Console.WriteLine("Setting User Password");
                newUser.Invoke("SetPassword", new object[] { userPassword });

                newUser.CommitChanges();

                Console.WriteLine("Adding itadmin to Administrators Group");
                admGroup.Invoke("Add", "WinNT://./" + newUser);

                Console.WriteLine("Cleaning Up");
                localMachine.Close();
                newUser.Close();
                admGroup.Close();
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }
            catch (System.Runtime.InteropServices.COMException E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }
            catch (System.Reflection.TargetInvocationException E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }
            catch (Exception E)
            {
                Console.WriteLine(E.Message.ToString());
                Console.ReadLine();
            }

            Console.WriteLine();
            Console.WriteLine("Press Any Key to Continue");
            Console.ReadLine();
            return;
        }
    }
}

The code output is below:代码输出如下:

Building System Information
Building User Information
Setting User Password
Adding itadmin to Administrators Group
Exception has been thrown by the target of an invocation.

Any insight would be greatly appriciated.任何见解都会非常有用。

UPDATE 1: With the help of @Grumbler85 the exceptionis listed below:更新 1:在@Grumbler85 的帮助下,下面列出了例外情况:

System.Reflection.TargetInvocationException: Exception has been thrown by the target 
of an invocation. ---> System.Runtime.InteropServices.COMException: A member could not
be added to or removed from the local group because the member does not exist. --- End
of inner exception stacktrace --- at System.DirectoryServices.DirectoryEntry.Invoke
(String methodName,Object[]args) at CreateITAdmin.Program.Main(String[]args)in 
H:\code\CS\CreateITAdmin\CreateITAdmin\Program.cs:line 37

Also with the help of @Grumbler85 I have been working on updating the library use to System.DirectoryServices.AccountManagement.同样在@Grumbler85 的帮助下,我一直致力于将库使用更新为 System.DirectoryServices.AccountManagement。 It seems to be a lot easier and a lot more straight forward in use.它在使用中似乎更容易和更直接。 More updates/details to come as I progress.随着我的进步,将有更多更新/详细信息。

Update 2: I know this is a quick follow up but I was able to complete the update to the new namespace.更新 2:我知道这是一个快速跟进,但我能够完成对新命名空间的更新。 After a minor hiccup with defining the machine, I was able to successfully create a user, set the password, update the password to never expire, and add the user to the administrators group.在定义机器时遇到了一些小问题,我成功地创建了一个用户,设置了密码,将密码更新为永不过期,并将用户添加到管理员组。 Thanks to @Grumbler85 for the update to the new namespace.感谢 @Grumbler85 更新新命名空间。 The new code is below:新代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace CreateITAdmin
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "itadmin";
            string userPassword = "IT-Engineering1";
            PrincipalContext systemContext = null;

            try
            {
                Console.WriteLine("Building System Information");
                systemContext = new PrincipalContext(ContextType.Machine, null);
            }
            catch (Exception E)
            {
                Console.WriteLine("Failed to create System Context.");
                Console.WriteLine("Exception: " + E);

                Console.WriteLine();
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadLine();
                return;
            }

            //Check if user object already exists
            Console.WriteLine("Checking if User Exists.");
            UserPrincipal usr = UserPrincipal.FindByIdentity(systemContext, userName);
            if (usr != null)
            {
                Console.WriteLine(userName + " already exists. Exiting!!");
                Console.ReadLine();
                return;
            }

            //Create the new UserPrincipal object
            Console.WriteLine("Building User Information");
            UserPrincipal userPrincipal = new UserPrincipal(systemContext);
            userPrincipal.Name = userName;
            userPrincipal.DisplayName = "IT Administrative User";
            userPrincipal.PasswordNeverExpires = true;
            userPrincipal.SetPassword(userPassword);
            userPrincipal.Enabled = true;

            try
            {
                Console.WriteLine("Creating New User");
                userPrincipal.Save();
            }
            catch (Exception E)
            {
                Console.WriteLine("Failed to create user.");
                Console.WriteLine("Exception: " + E);

                Console.WriteLine();
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadLine();
                return;
            }

            GroupPrincipal groupPrincipal = null;
            try
            {
                groupPrincipal = GroupPrincipal.FindByIdentity(systemContext, "Administrators");

                if (groupPrincipal != null)
                {
                    //check if user is a member
                    Console.WriteLine("Checking if itadmin is part of Administrators Group");
                    if (groupPrincipal.Members.Contains(systemContext, IdentityType.SamAccountName, userName))
                    {
                        Console.WriteLine("Administrators already contains " + userName);
                        return;
                    }
                    //Adding the user to the group
                    Console.WriteLine("Adding itadmin to Administrators Group");
                    groupPrincipal.Members.Add(userPrincipal);
                    groupPrincipal.Save();
                    return;
                }
                else
                {
                    Console.WriteLine("Could not find the group Administrators");
                }
            }
            catch (Exception E)
            {
                Console.WriteLine("Exception adding user to group.");
                Console.WriteLine("Exception: " + E);

                Console.WriteLine();
                Console.WriteLine("Press Any Key to Continue");
                Console.ReadLine();
            }

            Console.WriteLine("Cleaning Up");
            groupPrincipal.Dispose();
            userPrincipal.Dispose();
            systemContext.Dispose();

            Console.WriteLine();
            Console.WriteLine("Press Any Key to Continue");
            Console.ReadLine();
            return;
        }
    }
}

For Update 3 (for Multi Language support)对于更新 3(用于多语言支持)

Please use build in identifiers --> "Well Known SIDs" for build in accounts or groups:请使用内置标识符 --> “众所周知的 SID” 用于内置帐户或组:

var sAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid , null).Translate(typeof(NTAccount)).Value;

groupPrincipal = GroupPrincipal.FindByIdentity(systemContext, IdentityType.Name, sAdministrators.ToString());

and not: ..... FindByIdentity(systemContext, "Administrators");而不是: ..... FindByIdentity(systemContext, "Administrators");

Because if you want to use it "world wide" and outside of the engl.因为如果你想在“世界范围内”和 engl 之外使用它。 world you will get an error.世界你会得到一个错误。 Example: Germany use "VORDEFINIERT\\Administratoren" as Name.示例:德国使用“VORDEFINIERT\\Administratoren”作为名称。

You mention that these machines are on a domain, it is much simpler to just do this with group policy.您提到这些机器位于域中,使用组策略执行此操作要简单得多。

Go in to group policy management ( gpmc.msc ) and create a new policy.进入组策略管理 ( gpmc.msc ) 并创建一个新策略。 Once you have a new policy created go to Computer Configuration->Prefrences->Local Users and Groups .创建新策略后,转到“ Computer Configuration->Prefrences->Local Users and Groups在此处输入图片说明

From there right click and go to New->Local User .从那里右键单击并转到New->Local User In the new screen set the action to Create (you can click the help button to see the difference between the modes) and enter your info for the user in that screen.在新屏幕中,将操作设置为Create (您可以单击帮助按钮查看模式之间的差异)并在该屏幕中为用户输入您的信息。

在此处输入图片说明

One you click ok the user will show up on the screen on the local users and groups page.单击确定后,用户将显示在本地用户和组页面的屏幕上。 From there right click and go to New->Local Group .从那里右键单击并转到New->Local Group On the new page set the action to Update , use the drop-down to find the group name Administrators (built-in) and select it.在新页面上将操作设置为Update ,使用下拉列表找到组名Administrators (built-in)并选择它。 In the bottom section click Add... and type in by hand the same name you put in from the previous screen ( itadmin in your case).在底部单击Add...并手动输入您在前一个屏幕中输入的相同名称(在您的情况下为itadmin )。 At the end it should look like this最后它应该是这样的

在此处输入图片说明

the Local Users and Groups page will look like this本地用户和组页面将如下所示

在此处输入图片说明

It is important to notice the Order column, the update on the administrator's group must have a higher order number than the user creation command.重要的是要注意 Order 列,管理员组上的更新必须具有比用户创建命令更高的顺序号。

One you have your group policy set up apply the policy to the machines that are in the lab (be it through OU targeting or Security Filtering, or WMI Filtering).设置了组策略的一个将策略应用于实验室中的计算机(通过 OU 目标或安全过滤或 WMI 过滤)。 On next reboot the local itadmin user will be created on each machine.下次重新启动时,将在每台机器上创建本地 itadmin 用户。


Also a interesting note, when you choose the user when selecting who to add to the local administrators group, you can click the ... and choose a user on the domain this will allow someone to use their domain login to be a local admin on a small set of computers without giving them rights to be a admin everywhere.还有一个有趣的注意事项,当您在选择将谁添加到本地管理员组时选择用户时,您可以单击...并选择域上的用户这将允许某人使用其域登录成为本地管理员一小组计算机,而没有赋予他们在任何地方成为管理员的权利。 However they will need to be able to log in using the domain for this to work, so if you are troubleshooting a network connectivity issue your current approach may be a better thing to do.但是,他们需要能够使用域登录才能正常工作,因此如果您正在对网络连接问题进行故障排除,您当前的方法可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM