c# - 如何将用户加入Administrators Group

来源:互联网 发布:互联网寒冬 知乎 编辑:程序博客网 时间:2024/05/16 05:58

再写某些测试工具的时候,我们希望用户有Administrator权限.当然我们可以手动来做:我的电脑-〉管理-〉本地用户和组->管理员组->Add a user. 如果当前用户有足够权限的话, 我们可以手动的加其它用户到某个安全组里, 当然我们也可以用Script。

但是在c#里, 如何将用户加入机器的Administrators Group? 有没有可能在自己的机器把用户到其它机器的Adminstrators Group?

事实上, 在一个Domain里的所有机器的信息,域用户,安全组的信息 都存在一个叫Active Directory的树状结构的数据库里,它的特点是查询很快, 修改稍慢。使用System.DirectoryServices 命名空间下的类可以控制Active Directory可以对它进行查询, 修改。

因此,我们需要使用System.DirectoryServices下面一些类对Active Directory进行操作,可以查询某台机器的Adminstrators Group里面都有什么用户,也可添加或删除用户。

具体请参考这里:http://msdn.microsoft.com/zh-cn/library/system.directoryservices(v=vs.100).aspx

using System.DirectoryServices


            try            {                //Add user to local machine                //DirectoryEntry localGroup = new DirectoryEntry(String.Format("WinNT://{0}/{1}, group", Environment.MachineName, "Administrators"));                //DirectoryEntry remoteGroup = new DirectoryEntry(String.Format("WinNT://{0}/{1}", "domain", "username"), "domain\\username", "Pa$$word");//, AuthenticationTypes.Secure);                //localGroup.Invoke("Add", new object[] { remoteGroup.Path });                //localGroup.CommitChanges();                //Add user to remote machine.                DirectoryEntry remoteGroup1 = new DirectoryEntry(String.Format("WinNT://{0}/{1}, group", "RemoteMachineName", "Administrators"));                DirectoryEntry remoteUserGroup = new DirectoryEntry(String.Format("WinNT://{0}/{1}", "domain", "username"), "domain\\username", "Pa$$word");                remoteGroup1.Invoke("Add", new object[] { remoteUserGroup.Path });                remoteGroup1.CommitChanges();            }            catch (Exception ex)            {                throw ex;            }
原创粉丝点击