You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ubuntu Linux上用.NET Core 2.0内置类检测程序是否以sudo/管理员运行

如何在.NET Core 2.0的Ubuntu Linux上检测程序是否以sudo/管理员身份运行?

你的问题很典型——Windows平台的WindowsIdentity和WindowsPrincipal是专属API,在Linux上完全不支持,所以会抛出PlatformNotSupportedException。要在Ubuntu上检测是否以sudo/管理员(本质是root权限)运行,我们需要利用Linux系统自身的特性:root用户的ID(UID)永远是0,sudo启动的进程会临时获得root权限,此时进程的UID也是0。

下面是跨平台的实现方案,既能在Windows正常工作,也能在Linux上正确检测sudo权限:

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace smallTestsCore
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(IsRunningAsAdmin());
            Console.ReadLine();
        }

        public static bool IsRunningAsAdmin()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // Windows平台保持原有逻辑
                return new WindowsPrincipal(WindowsIdentity.GetCurrent())
                    .IsInRole(WindowsBuiltInRole.Administrator);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || 
                     RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // Linux/OSX平台检测UID是否为0(root权限)
                return getuid() == 0;
            }

            // 其他未知平台默认返回false
            return false;
        }

        // P/Invoke调用Linux libc的getuid()函数,获取当前进程的用户ID
        [DllImport("libc", SetLastError = true)]
        private static extern uint getuid();
    }
}

关键说明:

  • Windows分支:保留你原来的逻辑,因为它在Windows上能正确检测管理员权限。
  • Linux/OSX分支:通过P/Invoke调用系统的getuid()函数,直接获取当前进程的用户ID——如果返回0,说明进程拥有root权限(也就是通过sudo启动的)。
  • 兼容性:这个方法在.NET Core 2.0及以上版本都能正常工作,完全符合跨平台需求。

测试的时候,你可以用两种方式运行程序:

  • 普通用户运行:输出False
  • 用sudo dotnet run运行:输出True

内容的提问来源于stack exchange,提问作者Reven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:29:19