简体   繁体   English

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

[英]Programmatically getting UID and GID from username in Unix?

I'm trying to use setuid() and setgid() to set the respective id's of a program to drop privileges down from root, but to use them I need to know the uid and gid of the user I want to change to.我正在尝试使用 setuid() 和 setgid() 来设置程序的相应 id 以从 root 降低权限,但要使用它们,我需要知道我想要更改为的用户的 uid 和 gid。

Is there a system call to do this?是否有系统调用来执行此操作? I don't want to hardcode it or parse from /etc/passwd.我不想对其进行硬编码或从 /etc/passwd 进行解析。

Also I'd like to do this programmatically rather than using:我也想以编程方式执行此操作而不是使用:

id -u USERNAME id -u 用户名

Any help would be greatly appreciated任何帮助将不胜感激

Have a look at the getpwnam() and getgrnam() functions.查看getpwnam()getgrnam()函数。

#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;
}

You want to use the getpw* family of system calls, generally in pwd.h .您想要使用 getpw* 系统调用系列,通常在pwd.h中。 It's essentially a C-level interface to the information in /etc/passwd.它本质上是 /etc/passwd 中信息的 C 级接口。

You can use the following code snippets:您可以使用以下代码片段:

#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;
}

Ref: getpwnam() getgrnam()参考: getpwnam() getgrnam()

Look at getpwnam and struct passwd.查看 getpwnam 和 struct passwd。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM