【问题标题】:Using UserPrincipal to check if local admin使用 UserPrincipal 检查本地管理员是否
【发布时间】:2012-07-02 15:22:02
【问题描述】:

我正在尝试使用一种方法来接收用户名,如果该用户是本地管理员(不是在整个域上,只是在本地计算机上),则返回 true,否则返回 false。我试图改变在In .NET/C# test if process has administrative privileges 找到的技术来工作,但它没有。我曾尝试使用 NetUserGetInfo 方式,但无法使其正常工作。现在我正在尝试使用 UserPrincipal。下面的代码就是我所拥有的...主要只是测试基础知识是否有效。

PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId);

if(usr == null)
{
    Console.WriteLine("usr is null");
}
else
{
    Console.WriteLine(usr.Enabled);
    Console.WriteLine(usr.IsAccountLockedOut());

    foreach (Principal p in usr.GetAuthorizationGroups())
    {
        Console.WriteLine(p.ToString());   
    }
}

看起来我应该可以使用 isMemberOf 方法,但是如何为本地管理员创建一个组?或者有没有比 isMemberOf 方法更好的方法?

【问题讨论】:

    标签: c# active-directory admin active-directory-group userprincipal


    【解决方案1】:

    实际上我可以检查从 GetAuthorizationGroups()) 返回的 Principal 之一是否等于“Administators”。

    foreach (Principal p in usr.GetAuthorizationGroups())
    {
        if (p.ToString() == "Administrators")
        {
            result = true;
        }
    }
    

    【讨论】:

      【解决方案2】:

      另一种可能性。如果您从 UserPrincipal 对象获取 WindowsIdentity。您可以使用 IsInRole(groupname) 方法。

      你可以通过做得到 WindowsIdentity

      var identity = new WindowsIdentity(string sUserPrincipalName);
      
      // then use this method to check the Identity against any Active Directory group.
      public static bool UserIsInRole(WindowsIdentity identity, string group)
      {
          try
          {
              return new WindowsPrincipal(identity).IsInRole(group);
          }
          catch (Exception ex)
          {
              //Error checking role membership
              return false;
          }
      }
      

      【讨论】:

        【解决方案3】:

        这样就可以了

            static bool IsAdmin()
            {
                // net localgroup administrators
        
                var proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "net",
                        Arguments = "localgroup administrators",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
        
                proc.Start();
        
                var computer = new PrincipalContext(ContextType.Machine).ConnectedServer;
                var isAdmin = proc.StandardOutput.ReadToEnd().Contains(computer);
        
                return isAdmin;
            }
        

        【讨论】:

          猜你喜欢
          • 2018-02-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多