Reputation: 3
I want to print all groups of users stored in /etc/passwd. Seems easy enough, I can just use getpwent() and getgrouplist(). I came with this code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <grp.h>
int main(int argc, char** argv){
struct passwd* user;
int nGroups = 20;
gid_t* groups;
groups = malloc(nGroups * sizeof(gid_t));
struct group* gr;
while(user = getpwent()){
printf("%s : ", user->pw_name);
getgrouplist(user->pw_name, user->pw_gid, groups, &nGroups);
int i;
for(i = 0; i < nGroups; ++i){
gr = getgrgid(groups[i]);
if(gr){
printf("%s ", gr->gr_name);
}
}
printf("\n");
}
free(groups);
return 0;
}
It gives me this output:
root : root
daemon : daemon
bin : bin
.
.
.
pulse : pulse root
ricenwind : ricenwind adm root root root root root root
vboxadd : daemon
which is clearly wrong, as for example using
groups ricenwind
gives me:
ricenwind : ricenwind adm cdrom sudo dip plugdev lpadmin sambashare
Upvotes: 0
Views: 1024
Reputation: 1
You can achieve this using a simple bash script as
grep "/bin/bash" /etc/passwd
it would do the result,bcoz all the local user will have /bin/bash or /bin/sh as their shell
Upvotes: 0
Reputation: 409166
If you read the getgrouplist
manual page you will see
Up to
*ngroups
of these groups are returned in the arraygroups
.
The ngroups
argument is not only set by the function, it's also used by the function to know how many structures you have allocated for the groups
argument.
You need to "reset" the nGroups
variable before calling getgrouplist
, otherwise the old value set by the previous call to the function will be used:
nGroups = 20;
getgrouplist(user->pw_name, user->pw_gid, groups, &nGroups);
Upvotes: 1