检查用户是否是C的root用户?

时间:2010-11-11 22:29:23

标签: c unix root

如何验证用户是否为root用户?

3 个答案:

答案 0 :(得分:57)

通常,测试用户是否为root是错误的。 POSIX甚至不需要root用户,而是将其留给实现来确定权限的工作方式。代码如:

if (i_am_root) do_privileged_op(); else print_error();

将真正惹恼用户使用高级权限模型,其中root不需要执行必要的特权操作。我记得早在Linux上的CD刻录时,我不得不破解所有cdrecord来源以删除所有无用的检查以查看它是否以root身份运行,当它工作得很好并且具有读取权限时/dev/sga

相反,您应始终尝试您需要执行的特权操作,并检查EPERM或类似内容,如果它无法通知用户他们没有足够的权限(也许应该以root身份重试运行。

检查root是有用的一种情况是检查你的程序是否被调用“suid-root”。合理的测试是:

uid_t uid=getuid(), euid=geteuid();
if (uid<0 || uid!=euid) {
    /* We might have elevated privileges beyond that of the user who invoked
     * the program, due to suid bit. Be very careful about trusting any data! */
} else {
    /* Anything goes. */
}

请注意,我允许获取uid / euid的任何一个调用失败的可能性(牵强附会,但最好是偏执狂),并且在失败的情况下我们应该假设我们是suid并且是恶意的用户以某种方式导致系统调用失败,试图隐藏我们的suid。

答案 1 :(得分:31)

getuidgeteuid,取决于您的真实含义。在任何一种情况下,0表示root。

if(geteuid() != 0)
{
  // Tell user to run app as root, then exit.
}

R的观点是有效的。您应该考虑试错,或者其他没有明确要求root的方法。

答案 2 :(得分:0)

最好使用getuid或geteuid,但是它在zconf.h头文件中,因此必须像下面这样输入:

#include <zconf.h>
#include <stdio.h>
int main()
{
int a;
a=getuid();
//or you can use  a=geteuid();
//euid is effective user id and uid is user id 
// both euid and uid are zero when you are root user 
if (a==0){
printf("you are root user");
//so you can do what`enter code here`ever `enter code here` you want as root user
}
else
printf("please run the script as root user !");
return 0;
}