4

我正在尝试使用一种方法来接收用户名,如果该用户是本地管理员(不是在整个域上,只是在本地机器上),则返回 true,否则返回 false。我试图改变In .NET/C# test if process has administrator permissions to work 中发现的技术,但它没有。我曾尝试使用 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 方法更好的方法?

4

3 回答 3

5

好吧,实际上我能够检查从 GetAuthorizationGroups()) 返回的委托人之一是否等于“管理员”。

foreach (Principal p in usr.GetAuthorizationGroups())
{
    if (p.ToString() == "Administrators")
    {
        result = true;
    }
}
于 2012-07-02T15:42:08.930 回答
1

另一种可能。如果您从 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;
    }
}
于 2013-08-21T15:27:35.267 回答
0

这会做

    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;
    }
于 2020-09-01T12:28:26.827 回答