在Unix中以编程方式从用户名获取UID和GID?

时间:2009-06-17 20:06:11

标签: c++ c unix privileges system-calls

我正在尝试使用setuid()和setgid()来设置程序的相应id以从root删除权限,但要使用它们我需要知道我想要更改的用户的uid和gid到。

是否有系统调用来执行此操作?我不想硬编码或从/ etc / passwd解析。

此外,我想以编程方式而不是使用:

id -u USERNAME

非常感谢任何帮助

5 个答案:

答案 0 :(得分:20)

查看getpwnam()getgrnam()函数。

答案 1 :(得分:3)

您希望使用getpw *系列调用,通常在pwd.h中。它本质上是/ etc / passwd中信息的C级接口。

答案 2 :(得分:3)

#include <sys/types.h>
#include <pwd.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
    char *username = ...

    struct passwd *pwd = calloc(1, sizeof(struct passwd));
    if(pwd == NULL)
    {
        fprintf(stderr, "Failed to allocate struct passwd for getpwnam_r.\n");
        exit(1);
    }
    size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX) * sizeof(char);
    char *buffer = malloc(buffer_len);
    if(buffer == NULL)
    {
        fprintf(stderr, "Failed to allocate buffer for getpwnam_r.\n");
        exit(2);
    }
    getpwnam_r(username, pwd, buffer, buffer_len, &pwd);
    if(pwd == NULL)
    {
        fprintf(stderr, "getpwnam_r failed to find requested entry.\n");
        exit(3);
    }
    printf("uid: %d\n", pwd->pw_uid);
    printf("gid: %d\n", pwd->pw_gid);

    free(pwd);
    free(buffer);

    return 0;
}

答案 3 :(得分:1)

查看getpwnam和struct passwd。

答案 4 :(得分:0)

您可以使用以下代码段:

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

gid_t Sandbox::getGroupIdByName(const char *name)
{
    struct group *grp = getgrnam(name); /* don't free, see getgrnam() for details */
    if(grp == NULL) {
        throw runtime_error(string("Failed to get groupId from groupname : ") + name);
    } 
    return grp->gr_gid;
}

uid_t Sandbox::getUserIdByName(const char *name)
{
    struct passwd *pwd = getpwnam(name); /* don't free, see getpwnam() for details */
    if(pwd == NULL) {
        throw runtime_error(string("Failed to get userId from username : ") + name);
    } 
    return pwd->pw_uid;
}

参考:getpwnam() getgrnam()