如何在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
相关产品推荐
相关产品推荐

