简体   繁体   English

Mono上的WinForms / Console应用程序,如何知道它以root身份运行

[英]WinForms/Console application on Mono, how to know it runs as root

As we can execute such executables in two ways, such as "sudo mono test.exe", and "mono test.exe". 因为我们可以通过两种方式执行此类可执行文件,例如“sudo mono test.exe”和“mono test.exe”。

Now I want to know how to detect whether this application is running as root inside the application itself. 现在我想知道如何检测此应用程序是否在应用程序本身内以root身份运行。

I tried to check user name like below and see whether they equal to "root", 我试着查看下面的用户名,看看它们是否等于“root”,

Thread.CurrentPrincipal.Identity.Name Thread.CurrentPrincipal.Identity.Name

Process.GetCurrentProcess().StartInfo.UserName Process.GetCurrentProcess()。StartInfo.UserName

AppDomain.CurrentDomain.ApplicationIdentity.FullName AppDomain.CurrentDomain.ApplicationIdentity.FullName

The first two are empty strings always, while the third throws NullReferenceException. 前两个总是空字符串,而第三个抛出NullReferenceException。

Please advise if this is doable on Mono 2.6. 请告知Mono 2.6是否可行。

One solution is to DllImport libc and use the getuid() function. 一种解决方案是使用DllImport libc并使用getuid()函数。 If you're running as root, getuid() returns 0; 如果你以root身份运行, getuid()将返回0; if not, it returns some other UID: 如果没有,它返回一些其他UID:

using System.Runtime.InteropServices;

public class Program
{
    [DllImport ("libc")]
    public static extern uint getuid ();

    public static void Main()
    {
        if (getuid() == 0) {
            System.Console.WriteLine("I'm running as root!");
        } else {
            System.Console.WriteLine("Not root...");
        }
    }
}

This works fine in Mono 2.6. 这在Mono 2.6中运行良好。

EDIT: It might be better to access getuid() through the Mono.Unix.Native.Syscall wrapper class in the Mono.Posix assembly: 编辑:通过Mono.Posix程序集中的Mono.Unix.Native.Syscall包装类访问getuid()可能更好:

using Mono.Unix.Native;

public class Program
{
    public static void Main()
    {
        if (Syscall.getuid() == 0) {
            System.Console.WriteLine("I'm running as root!");
        } else {
            System.Console.WriteLine("Not root...");
        }
    }
}

Sorry, I'm not much of a Mono expert. 对不起,我不是Mono专家。 But however you get to it, the process's UID is what you want to know; 但无论你怎么做,这个过程的UID都是你想知道的; if it's equal to zero then you're root, otherwise you're not root. 如果它等于零那么你就是root,否则你就不是root。

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

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