如何确定进程所有者是否是C ++中Mac OS X的管理员

时间:2012-06-14 01:29:13

标签: c++ macos

如何以编程方式检查运行我的可执行文件的用户是否为管理员?

这是Mac OS X 10.6(Snow Leopard)或更高版本的C ++。我的许多搜索都没有发现任何内容。

4 个答案:

答案 0 :(得分:2)

检查用户所在的groups,并确认该用户位于所需的群组中。我想您要检查用户是否属于“admin”,但您可能希望检查其他更具体的访问权限。你为什么要检查管理员呢?直接尝试任务通常是一个更好的想法,而不是检查广泛的访问级别,如果用户没有该访问权限,则会失败,但实际上具有您想要的特定访问权限。

答案 1 :(得分:0)

如何通过调用getuid()来检查用户ID? OS X基于BSD。因此,我认为您可以检查通过此函数运行该过程的用户ID。

答案 2 :(得分:0)

#include <grp.h>
#include <pwd.h>
#include <string.h>

bool currentUserIsAdmin ( ) {
    // A user cannot be member in more than NGROUPS groups,
    // not counting the default group (hence the + 1)
    gid_t groupIDs[NGROUPS + 1];
    // ID of user who started the process
    uid_t userID = getuid();
    // Get user password info for that user
    struct passwd * pw = getpwuid(userID);

    int groupCount;
    if (pw) {
        // Look up groups that user belongs to
        groupCount = NGROUPS + 1;
        // getgrouplist returns ints and not gid_t and
        // both may not necessarily have the same size
        int intGroupIDs[NGROUPS + 1];
        getgrouplist(pw->pw_name, pw->pw_gid, intGroupIDs, &groupCount);
        // Copy them to real array
        for (int i = 0; i < groupCount; i++) groupIDs[i] = intGroupIDs[i];

    } else {
        // We cannot lookup the user but we can look what groups this process
        // currently belongs to (which is usually the same group list).
        groupCount = getgroups(NGROUPS + 1, groupIDs);
    }

    for (int i = 0; i < groupCount; i++) {
        // Get the group info for each group
        struct group * group = getgrgid(groupIDs[i]);
        if (!group) continue;
        // An admin user is member of the group named "admin"
        if (strcmp(group->gr_name, "admin") == 0) return true;
    }
    return false;
}

答案 3 :(得分:-1)

看起来Open Directory是正确的方法。您可以使用getegid()和/或setegid()

来降低费用

我没有测试过,但这可能有用:

// 80 should be the admin group number, but it Apple might change it in a later release.
if (getegid() == 80 || setegid(80) == 0) {
    // Yea! I'm an admin.
}

只需要几个简单的想法即可跟进。我希望他们能引导你朝着正确的方向前进。