如何以编程方式检查运行我的可执行文件的用户是否是管理员?
这是 Mac OS X 10.6 (Snow Leopard) 或更高版本上的 C++。我的许多搜索都没有发现任何东西。
检查groups
用户是否在其中,并确认该用户在所需的组中。我认为您想检查用户是否属于“管理员”,但您可能想检查其他更具体的访问权限。你为什么要检查管理员呢?直接尝试该任务通常是一个更好的主意,而不是检查广泛的访问级别并在用户没有该访问权限但实际上具有您想要的特定访问权限时失败。
通过调用 getuid() 检查用户 ID 怎么样?OS X 基于 BSD。因此,我认为您可以通过此功能检查运行进程的 ID。
#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;
}
看起来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.
}
只需几个快速的想法即可跟进。我希望他们能引导你朝着正确的方向前进。