Mono 上的 WinForms/Console 应用程序,如何知道它以 root 身份运行
因为我们可以通过两种方式执行此类可执行文件,例如“sudo mono test.exe”和“mono test.exe”。
现在我想知道如何检测该应用程序是否在应用程序本身内以 root 身份运行。
我尝试像下面这样检查用户名,看看它们是否等于“root”,
Thread.CurrentPrincipal.Identity.Name
Process.GetCurrentProcess().StartInfo.UserName
AppDomain.CurrentDomain.ApplicationIdentity.FullName
前两个始终是空字符串,而第三个抛出 NullReferenceException。
请告知这在 Mono 2.6 上是否可行。
As we can execute such executables in two ways, such as "sudo mono test.exe", and "mono test.exe".
Now I want to know how to detect whether this application is running as root inside the application itself.
I tried to check user name like below and see whether they equal to "root",
Thread.CurrentPrincipal.Identity.Name
Process.GetCurrentProcess().StartInfo.UserName
AppDomain.CurrentDomain.ApplicationIdentity.FullName
The first two are empty strings always, while the third throws NullReferenceException.
Please advise if this is doable on Mono 2.6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案是
DllImport
libc 并使用getuid()
函数。如果您以 root 身份运行,getuid()
返回 0;如果没有,它会返回一些其他 UID:这在 Mono 2.6 中工作得很好。
编辑:通过 Mono.Posix 程序集中的 Mono.Unix.Native.Syscall 包装类访问 getuid() 可能会更好:
抱歉,我不是 Mono 专家。但无论您如何了解,您都想知道进程的 UID;如果它等于零那么你就是root,否则你就不是root。
One solution is to
DllImport
libc and use thegetuid()
function. If you're running as root,getuid()
returns 0; if not, it returns some other UID:This works fine in Mono 2.6.
EDIT: It might be better to access
getuid()
through the Mono.Unix.Native.Syscall wrapper class in the Mono.Posix assembly:Sorry, I'm not much of a Mono expert. But however you get to it, the process's UID is what you want to know; if it's equal to zero then you're root, otherwise you're not root.