Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get linux user id by user name?

Tags:

c

linux

In linux, If I only have the user name, how to get the user id? I used man getuid, but can't find any clues about it. EDIT1: Sorry , I want to get the user id by api. I don't like forking a another process to do it such as calling system function.

like image 343
jaslip Avatar asked Aug 26 '16 03:08

jaslip


People also ask

How do I find user ID in Linux?

In Linux, the /etc/passwd file stores the user information, such as the user's name, UID, group id (GID), user's home directory, and user's shell. We can get the username by parsing the /etc/passwd file.

How do I print a user ID in Linux?

-G, --groups: It is used to print all group Ids. -n, --name: It is used to print a name instead of a number. -r, --real: It is used to print the real ID instead of the effective ID, with -ugG. -u, --user: It is used to print only the effective UID.

How do I find my UID username?

How to get Username from UID in Linux. Although, there is no built in command get fetch the username from the UID. We can use a pipe and regular expression match on getent to do that. getent is a unix command that helps a user get entries in a number of important text files called databases.


2 Answers

You can use getpwnam to get a pointer to a struct passwd structure, which has pw_uid member. 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.

like image 77
Alok Singhal Avatar answered Sep 21 '22 17:09

Alok Singhal


Simply use the id command

id username

[root@my01 ~]# id sylvain
uid=1003(sylvain) gid=1005(sylvain) groups=1005(sylvain)
like image 28
Sylwit Avatar answered Sep 18 '22 17:09

Sylwit