简体   繁体   English

如何通过用户名获取linux用户ID?

[英]How to get linux user id by user name?

In linux, If I only have the user name, how to get the user id? 在linux中,如果我只有用户名,如何获取用户ID? I used man getuid, but can't find any clues about it. 我用man getuid,但找不到任何关于它的线索。 EDIT1: Sorry , I want to get the user id by api. EDIT1:对不起,我想通过api获取用户ID。 I don't like forking a another process to do it such as calling system function. 我不喜欢分支另一个进程来调用系统函数。

You can use getpwnam to get a pointer to a struct passwd structure, which has pw_uid member. 您可以使用getpwnam获取指向struct passwd结构的指针,该struct passwd具有pw_uid成员。 Example program: 示例程序:

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

int main(int argc, char *argv[])
{
    const char *name = "root";
    struct passwd *p;
    if (argc > 1) {
        name = argv[1];
    }
    if ((p = getpwnam(name)) == NULL) {
        perror(name);
        return EXIT_FAILURE;
    }
    printf("%d\n", (int) p->pw_uid);
    return EXIT_SUCCESS;
}

If you want a re-entrant function, look into getpwnam_r . 如果您想要一个可重入函数,请查看getpwnam_r

Simply use the id command 只需使用id命令即可

id username

[root@my01 ~]# id sylvain
uid=1003(sylvain) gid=1005(sylvain) groups=1005(sylvain)

所有用户名都列在/etc/passwd ,因此您可以grep和cut:

grep username /etc/passwd | cut -f3 -d':'

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

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