Monday, January 2, 2012

How to list all users of the given group (Linux)

Let's say I have a group name and I want function that lists all users of this group.

From the first point of view, the solutions is obvious. There is a function getgrnam which returns a pointer to struct group which has array of strings gr_mem (type "man getgrnam" for details). So we need to call the function and iterate through gr_mem until we meet NULL.

However, this is not accurate.  The problem is that this function parses the group databases. Some users may be not present in the group database but may have group id set as a field in /etc/passwd. So we need to iterate through all users to find those of them who have group id equal to the id of the given group.

The following code illustrates this approach. Please note that it is a sample only. In the real project you will need to check for duplicates because some users may be listed twice.

#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <stdio.h>

void list_all_users(const char *groupname) {
  struct group *grp = getgrnam(groupname);

  if (grp) {
    unsigned int i = 0;
    struct passwd *user_info;

    printf("group %s has the following members:\n", groupname);

     /* iterate through groups database */
    while (grp->gr_mem[i]) {
      printf("  %s\n", grp->gr_mem[i]);
    }

    for (user_info = getpwent(); user_info; user_info = getpwent()) {
      if (user_info->pw_gid == grp->gr_gid) {
        printf("  %s\n", user_info->pw_name);
      }
    }

    endpwent();
  } else {
    printf("group %s not found", groupname);
  }

}

No comments:

Post a Comment