简体   繁体   English

如何判断我的进程是否以管理员身份运行?

[英]How can I tell if my process is running as Administrator?

I would like to display some extra UI elements when the process is being run as Administrator as opposed to when it isn't, similar to how Visual Studio 2008 displays 'Administrator' in its title bar when running as admin.我想在进程以管理员身份运行时显示一些额外的 UI 元素,而不是在进程以管理员身份运行时,这类似于 Visual Studio 2008 在以管理员身份运行时在其标题栏中显示“管理员”的方式。 How can I tell?我怎么知道?

Technically, if you want to see if the member is the local administrator account , then you can get the security identifier (SID) of the current user through the User property on the WindowsIdentity class , like so (the static GetCurrent method gets the current Windows user):从技术上讲,如果要查看成员是否为本地管理员帐户,则可以通过WindowsIdentity上的User属性获取当前用户的安全标识符 (SID) ,如下所示(静态GetCurrent方法获取当前 Windows用户):

WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

string sid = windowsIdentity.User.ToString();

The User property returns the SID of the user which has a number of predefined values for various groups and users . User属性返回User的 SID,该 SID为各种组和用户提供了许多预定义的值

Then you would check to see if the SID has the following pattern, indicating it is the local administrator account (which is a well-known SID) :然后您将检查SID 是否具有以下模式,表明它是本地管理员帐户(这是一个众所周知的 SID)

S-1-5- {other SID parts} -500 S-1-5- {其他 SID 部件} -500

Or, if you don't want to parse strings, you can use the SecurityIdentifier class:或者,如果您不想解析字符串,可以使用SecurityIdentifier类:

// Get the built-in administrator account.
var sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, 
    null);

// Compare to the current user.
bool isBuiltInAdmin = (windowsIdentity.User == sid);

However, I suspect that what you really want to know is if the current user is a member of the administrators group for the local machine.但是,我怀疑您真正想知道的是当前用户是否是本地计算机管理员的成员。 You can get this SID using the WellKnownSidType of BuiltinAdministratorsSid :您可以使用得到这个SID WellKnownSidTypeBuiltinAdministratorsSid

// Get the SID of the admin group on the local machine.
var localAdminGroupSid = new SecurityIdentifier(
    WellKnownSidType.BuiltinAdministratorsSid, null);

Then you can check the Groups property on the WindowsIdentity of the user to see if that user is a member of the local admin group, like so:然后,您可以检查用户的WindowsIdentity上的Groups属性,以查看该用户是否是本地管理员组的成员,如下所示:

bool isLocalAdmin = windowsIdentity.Groups.
    Select(g => (SecurityIdentifier) g.Translate(typeof(SecurityIdentifier))).
    Any(s => s == localAdminGroupSid);

I think this is a good simple mechanism.我认为这是一个很好的简单机制。

using System.Security.Principal;

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

Here's a one liner to do it.这是一个单班轮来做到这一点。

using System.Security.Principal;

static bool IsElevated => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);

I felt it important to note the difficulty I had with attempting to use WellKnownSidType.BuiltinAdministratorsSid per casperOne's answer above.我觉得重要的是要注意根据上面 casperOne 的答案尝试使用 WellKnownSidType.BuiltinAdministratorsSid 时遇到的困难。 According to the WellKnownSiDType MSDN , BuiltinAdministratorsSid "Indicates a SID that matches the administrator account."根据 WellKnownSiDType MSDN ,BuiltinAdministratorsSid“表示与管理员帐户匹配的 SID。” So I would expect casperOne's code to work, and guess it likely does in some environments.所以我希望 casperOne 的代码能够工作,并且猜测它可能在某些环境中工作。 Unfortunately, it didn't on my Windows 2003 with .NET 2.0 (legacy code).不幸的是,它在我的带有 .NET 2.0(旧代码)的 Windows 2003 上没有。 It actually returned S-1-5-32-544 which, according to this article is the sid for the Administrators group .它实际上返回了 S-1-5-32-544,根据本文,它是 Administrators的 sid。 Thus, the comparison fails for me.因此,比较对我来说失败了。 I will have to do my own string comparison for startswith "S-1-5-21" (that kb 243330 indicates the "21" is included even though the blog referenced above does not) and endswith "500".我将不得不对startswith“S-1-5-21”(即kb 243330表示包括“21”,即使上面引用的博客没有)进行自己的字符串比较,并以“500”结尾。

I hope you solved it, I was looking for someone smart to solve my NamedPipe permission issue, perhaps someone in 2022 likes my answer to your 13-year-old question...我希望你解决了它,我正在寻找聪明的人来解决我的 NamedPipe 权限问题,也许 2022 年有人喜欢我对你 13 岁问题的回答......

using .net 6.0 > win7 or later...使用 .net 6.0 > win7 或更高版本...

Perhaps do something like this and test if what you see makes sense on your account:也许做这样的事情并测试您看到的内容是否对您的帐户有意义:

var user = WindowsIdentity.GetCurrent();
if (user is not null)
{

    logger.LogInformation("{User}", user.Name);
    foreach (var item in Enum.GetValues<WellKnownSidType>())
    {
        try
        {
            var sid = new SecurityIdentifier(item, user.Owner);
            logger.LogInformation($"IsIsWellKnown({item}): {user.Claims.Any(a=> a.Value == sid.Value)}");
        }
        catch { }
    }
}

then if it does you can use something like this:那么如果可以的话,你可以使用这样的东西:

public static bool Is(WindowsIdentity user, WellKnownSidType type)
{
    var sid = new SecurityIdentifier(type, user.Owner);
    return user.Claims.Any(a => a.Value == sid.Value);
}

You could be really smart about it and make an extension method by adding the this keyword您可能真的很聪明,并通过添加this关键字来创建扩展方法

public static bool Is(this WindowsIdentity user, WellKnownSidType type)
{
    var sid = new SecurityIdentifier(type, user.Owner);
    return user.Claims.Any(a => a.Value == sid.Value);
}

You could then use it like so:然后你可以像这样使用它:

WindowsIdentity.GetCurrent().Is(WellKnownSidType.AccountDomainAdminsSid))

I use simple try catch statement to create a random file in "C:\\Windows\\" folder.我使用简单的 try catch 语句在“C:\\Windows\\”文件夹中创建一个随机文件。 If it errors out the app is running with normal privileges otherwise it is running as admin privileges.如果出错,则应用程序以普通权限运行,否则以管理员权限运行。

        try
        {
            File.Create(string.Format(@"C:\Windows\{0}.txt", new Guid()), 0, FileOptions.DeleteOnClose);
            // Do as admin
        }
        catch
        {
            // Do as default
        }

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

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