Qt,Linux,检查给定用户是否具有sudo权限

时间:2012-07-01 11:18:47

标签: linux qt qt4 sudo sudoers

我正在运行Fedora 17 KDE x64和Qt 4.8.1。

与Ubuntu相反,Fedora不会为第一个创建的用户提供sudo权限,也不会将第一个创建的用户添加到/etc/sudoers文件中。因此,当在Fedora 17 KDE上安装程序时(尚未测试Gnome等旋转),它需要root(不是sudo)权限。因此,我们有三个级别的权限(根据权限级别按降序排列):

1)root 2)sudo 3)用户

在Fedora 17 KDE中,如果您有权访问root用户帐户,只需编辑sudo文件并添加以下行即可向所需的任何其他用户授予/etc/sudoers权限:

user ALL = (ALL) ALL

......在线下:

root ALL = (ALL) ALL

user替换为您希望sudo访问的帐户的名称。

但并非每个用户都可以访问root用户的帐户。这就是root用户可以为某些用户帐户授予超级用户(sudo)权限的原因。

我想要检查运行应用程序的当前用户是否注册为超级用户。如果是这样,我会使/usr/bin/kdesu工具使用/usr/bin/sudo工具,该工具会询问sudo密码。

如果用户不是超级用户,我会保持/usr/bin/kdesu的行为与默认情况相同 - 它使用需要/usr/bin/su密码的root工具。

目前,我正在使用getenv('USER')(Windows上的“USERNAME”,但我只需要在Linux上使用此功能)来获取当前用户。可以通过遍历列出HOSTNAME和USER变量的QProcess::systemEnvironment()来获取当前用户的名称。

解析/etc/sudoers文件不是一个选项,因为打开文件需要sudoroot权限。

2 个答案:

答案 0 :(得分:3)

   man sudo
   [...]
   -l[l] [command]
               If no command is specified, the -l (list)
               option will list the allowed (and forbidden)
               commands for the invoking user (or the user
               specified by the -U option) on the current
               host.  If a command is specified and is
               permitted by sudoers, the fully-qualified
               path to the command is displayed along with
               any command line arguments.  If command is
               specified but not allowed, sudo will exit
               with a status value of 1.  If the -l option
               is specified with an l argument (i.e. -ll),
               or if -l is specified multiple times, a
               longer list format is used.

更新您需要一个(伪)终端才能运行sudo。这是一种方法:

#include <pty.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

int main (int argc, char* argv[])
{

    int status, master;
    pid_t respid, pid = forkpty (&master, 0, 0, 0);
    if (pid == 0) {
        /* we are child */
        argv[0] = "/usr/bin/sudo"; /* I know it's a sin... just for a demo */
        execve("/usr/bin/sudo", argv, 0);
    }
    else if (pid > 0) {
        /* we are parent */
        respid = waitpid(pid, &status, 0);
        fprintf (stderr, "sudo exited with status %d\n", 
                   WEXITSTATUS(status));
        }
    }
    else {
        fprintf (stderr, "could not forkpty\n");
    }
}

运行此代码:runsudo -lrunsudo -l /foo/bar/baz例如。

答案 1 :(得分:0)

请在单行脚本下运行。
它将列出所有具有sudo权限而没有sudo权限的用户:

for i in $(awk -F ':' '{print $1}' /etc/passwd ); do sudo -l -U $i ; done