C
C#6mo ago
bakane

How to check if program is running as root on Linux

I need my program to be run as sudo to function, so I want to exit if it's not. How can I check if the program is running as root? I can't find any method that gets you the euid.
5 Replies
NileshGR
NileshGR6mo ago
Environment.UserName Property (System)
Gets the user name of the person who is associated with the current thread.
cap5lut
cap5lut6mo ago
this should also work platform independent
public static bool IsRootUser()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using (var identity = WindowsIdentity.GetCurrent())
{
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
else
{
return geteuid() == 0;

[DllImport("libc")]
static extern uint geteuid();
}
}
public static bool IsRootUser()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using (var identity = WindowsIdentity.GetCurrent())
{
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
else
{
return geteuid() == 0;

[DllImport("libc")]
static extern uint geteuid();
}
}
bakane
bakaneOP6mo ago
Thanks!
HtmlCompiler
HtmlCompiler6mo ago
GitHub
Champion "static local functions" (16.3, Core 3) · Issue #1565 · do...
The proposal is to declare a local function as non-capturing. The keyword to indicate that would be static. Note: if we do this, then we should also consider allowing parameters and locals of the l...
cap5lut
cap5lut6mo ago
well, its an extern function, so it wont capture anything anyway ⤴️ will be lowered to
public static class C
{
public static bool IsRootUser()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
try
{
return new WindowsPrincipal(current).IsInRole(WindowsBuiltInRole.Administrator);
}
finally
{
if (current != null)
{
((IDisposable)current).Dispose();
}
}
}
return <IsRootUser>g__geteuid|0_0() == 0;
}

[DllImport("libc", EntryPoint = "geteuid")]
[CompilerGenerated]
internal static extern uint <IsRootUser>g__geteuid|0_0();
}
public static class C
{
public static bool IsRootUser()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
try
{
return new WindowsPrincipal(current).IsInRole(WindowsBuiltInRole.Administrator);
}
finally
{
if (current != null)
{
((IDisposable)current).Dispose();
}
}
}
return <IsRootUser>g__geteuid|0_0() == 0;
}

[DllImport("libc", EntryPoint = "geteuid")]
[CompilerGenerated]
internal static extern uint <IsRootUser>g__geteuid|0_0();
}
Want results from more Discord servers?
Add your server