添加本地用户以本地管理员组管理员、用户

2023-09-04 01:15:31 作者:无忘心安、

我写一个C#程序被推出我的工作在实验室。该方案是创建一个本地管理员帐户(itadmin),设置密码,将密码设置为永不过期,而该帐户添加到本地管理员组。该程序创建新的用户帐户,并正确设置一切,但是当它试图将其添加到管理员组中我得到一个非常不起眼的例外。我是否有添加到组正确的摆在首位?我在想什么?

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.DirectoryServices中;

命名空间CreateITAdmin
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            尝试
            {
                字符串username =itadmin;
                字符串的userPassword =密码;

                Console.WriteLine(建设系统信息);
                的DirectoryEntry LOCALMACHINE =新的DirectoryEntry(WINNT://.,computer);
                的DirectoryEntry新用户= localMachine.Children.Add(用户名,用户);
                的DirectoryEntry admGroup =新的DirectoryEntry(WINNT://./Administrators,group);

                Console.WriteLine(建设用户信息);
                。newUser.Properties [全名] =价值的IT管理用户;
                newUser.Invoke(放,新的对象[] {UserFlags,为0x10000});

                Console.WriteLine(设置用户密码);
                newUser.Invoke(SetPassword,新的对象[] {userPassword的});

                newUser.CommitChanges();

                Console.WriteLine(添加itadmin到管理员组);
                admGroup.Invoke(添加,WINNT://./+新用户);

                Console.WriteLine(清理);
                localMachine.Close();
                newUser.Close();
                admGroup.Close();
            }
            赶上(System.DirectoryServices.DirectoryServicesCOMException E)
            {
                Console.WriteLine(E.Message.ToString());
                到Console.ReadLine();
            }
            赶上(System.Runtime.InteropServices.COMException E)
            {
                Console.WriteLine(E.Message.ToString());
                到Console.ReadLine();
            }
            赶上(System.Reflection.TargetInvocationException E)
            {
                Console.WriteLine(E.Message.ToString());
                到Console.ReadLine();
            }
            赶上(例外五)
            {
                Console.WriteLine(E.Message.ToString());
                到Console.ReadLine();
            }

            Console.WriteLine();
            Console.WriteLine(preSS任意键继续);
            到Console.ReadLine();
            返回;
        }
    }
}
 

在code输出如下:

 建筑系统信息
构建用户信息
设置用户密码
添加itadmin到管理员组
异常被抛出调用的目标。
 

任何有识之士将大大appriciated。

更新1: 随着@ Grumbler85下列exceptionis的帮助:

  System.Reflection.TargetInvocationException:异常被抛出的目标
的调用。 ---> System.Runtime.InteropServices.COMException:成员不能
是添加或删除从本地组中,因为成员不存在。 - - 结束
内部异常堆栈跟踪---在System.DirectoryServices.DirectoryEntry.Invoke
(字符串方法名,对象[]参数)在CreateITAdmin.Program.Main(字串[] args)的
H:\ code \ CS \ CreateITAdmin \ CreateITAdmin \的Program.cs:行37
 
加入域控后,如何禁止客户端除administrator之外所有本地用户名 包括其他管理员账号

另外随着@ Grumbler85我一直在更新库的使用,以System.DirectoryServices.AccountManagement的帮助。这似乎是一个更容易和更大量直接的使用。更多更新/详细信息来作为我进步。

更新2: 我知道这是一个快速跟进,但我能完成更新,以新的命名空间。未成年人打嗝界定机器后,我是能够成功地创建一个用户,设置密码,更新密码永不过期,并且将用户添加到管理员组。感谢@ Grumbler85进行更新,以新的命名空间。新的code是如下:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.DirectoryServices中;
使用System.DirectoryServices.AccountManagement;

命名空间CreateITAdmin
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            字符串username =itadmin;
            字符串的userPassword =IT-Engineering1;
            PrincipalContext systemContext = NULL;

            尝试
            {
                Console.WriteLine(建设系统信息);
                systemContext =新PrincipalContext(ContextType.Machine,NULL);
            }
            赶上(例外五)
            {
                Console.WriteLine(无法创建的系统内容。);
                Console.WriteLine(异常:+ E);

                Console.WriteLine();
                Console.WriteLine(preSS任意键继续);
                到Console.ReadLine();
                返回;
            }

            //检查用户对象已存在
            Console.WriteLine(检查,如果用户存在。);
            UserPrincipal USR = UserPrincipal.FindByIdentity(systemContext,用户名);
            如果(USR!= NULL)
            {
                Console.WriteLine(用户名+。已存在退出!!);
                到Console.ReadLine();
                返回;
            }

            //创建新的UserPrincipal对象
            Console.WriteLine(建设用户信息);
            UserPrincipal userPrincipal =新UserPrincipal(systemContext);
            userPrincipal.Name =用户名;
            userPrincipal.DisplayName =IT管理用户;
            userPrincipal.PasswordNeverExpires = TRUE;
            userPrincipal.SetPassword(userPassword的);
            userPrincipal.Enabled = TRUE;

            尝试
            {
                Console.WriteLine(创建新用户);
                userPrincipal.Save();
            }
            赶上(例外五)
            {
                Console.WriteLine(无法创建用户。);
                Console.WriteLine(异常:+ E);

                Console.WriteLine();
                Console.WriteLine(preSS任意键继续);
                到Console.ReadLine();
                返回;
            }

            GroupPrincipal groupPrincipal = NULL;
            尝试
            {
                groupPrincipal = GroupPrincipal.FindByIdentity(systemContext,管理员);

                如果(groupPrincipal!= NULL)
                {
                    //检查,如果用户是一个成员
                    Console.WriteLine(察看itadmin是管理员组的一部分);
                    如果(groupPrincipal.Members.Contains(systemContext,IdentityType.SamAccountName,用户名))
                    {
                        Console.WriteLine(管理员已经包含了+用户名);
                        返回;
                    }
                    //添加用户到组
                    Console.WriteLine(添加itadmin到管理员组);
                    groupPrincipal.Members.Add(userPrincipal);
                    groupPrincipal.Save();
                    返回;
                }
                其他
                {
                    Console.WriteLine(无法找到该组管理员);
                }
            }
            赶上(例外五)
            {
                Console.WriteLine(异常将用户添加到组。);
                Console.WriteLine(异常:+ E);

                Console.WriteLine();
                Console.WriteLine(preSS任意键继续);
                到Console.ReadLine();
            }

            Console.WriteLine(清理);
            groupPrincipal.Dispose();
            userPrincipal.Dispose();
            systemContext.Dispose();

            Console.WriteLine();
            Console.WriteLine(preSS任意键继续);
            到Console.ReadLine();
            返回;
        }
    }
}
 

解决方案

我觉得这是种Shoe或玻璃瓶问题,所以我会给你用锤子一点教训。

您提到,这些机器都在一个域,它是非常简单的,只是这样与组策略。

进去组策略管理( GPMC.MSC ),并创建新的策略。一旦你创建了一个新的政策去计算机配置> prefrences->本地用户和组

从那里右键单击并转到新建 - >本地用户。在新的屏幕将操作设置为创建(您可以点击帮助按钮查看模式之间的差异),并输入在屏幕上,用户的信息。

一点击确定后,用户将显示在本地用户和组页上的屏幕上。从那里,点击右键,进入新建 - >本地组。在设定动作更新新的页面,使用下拉找到组名称管理​​员(内置)并选择它。在底部点击添加... 和手工输入您从previous屏幕放( itadmin 你的情况)。在结束就应该是这样的。

本地用户和组页面看起来像这样

要注意顺序列是很重要的,在管理员组的更新必须比用户创建命令一个更高的订单号。

一,你有你的组策略设置策略适用于在实验室(无论是通过OU目标或安全筛选,或WMI过滤)的设备。在下次重新启动本地itadmin用户将在每台机器上创建。

另外一个有趣的注意,当你选择谁添加到本地管理员组,当用户选择,您可以点击 ... 键,选择一个用户的的的域的这将允许其他人使用自己的域登录是在一个小套计算机的本地管理员不给他们做个管理员无处不在的权利。不过,他们需要能够登录使用这个工作的领域,所以如果你排除网络连接问题你目前的做法可能是一个更好的事情。

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. 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:

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. 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. 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. 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;
        }
    }
}

解决方案

I feel this is kind of a Shoe or Glass bottle question, so I will give you a little lesson on using a hammer.

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. Once you have a new policy created go to Computer Configuration->Prefrences->Local Users and Groups.

From there right click and go to 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.

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. On the new page set the action to Update, use the drop-down to find the group name Administrators (built-in) and select it. 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). 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.

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). On next reboot the local itadmin user will be created on each machine.

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.