How to get groupname when I have the groupid

2020-07-06 07:03发布

I have the parameters (especially the userid and the groupid) of a file read with the stat command and I work in a network where the users and groups are specified on an ldap server.

I've got the username out of the result of the command getent passwd userid.

Now my idea was to get the groupname with getent group groupid, but this doesn't work.

Can anyone tell me where I have my mistake or how I get the groupname?

Thanks!

标签: linux bash ldap
2条回答
Fickle 薄情
2楼-- · 2020-07-06 07:43

You probably have a configuration issue where either you've not got a line like:

group:    files ldap

in your /etc/nsswitch.conf.

or your group information on the ldap server is in a form that doesn't have group id numbers e.g. of type groupOfNames, groupOfUniqueNames instead of being of type posixGroup.

Only posixGroup has the appropriate attributes that permit it's use as a valid group in linux/unix (i.e. the group id number which is needed to match). In that situation the ldap server doesn't return valid groups.

You can have a perfectly functioning ldap configuration without any or all the remote groups being present in the output from getent group.

查看更多
霸刀☆藐视天下
3楼-- · 2020-07-06 08:01

Leaving aside the possibility that you're supplying a wrong group ID, this might be a bug in LDAP setup, which manifests in reverse group resolution not working. This is reinforced by the fact that this works on a plain "files" setup.

The getent(1) states:

group     When no key is provided, use setgrent(3), getgrent(3), and
          endgrent(3) to enumerate the group database.  When one  or
          more  key arguments are provided, pass each numeric key to
          getgrgid(3) and each nonnumeric  key  to  getgrnam(3)  and
          display the result.

This could mean that getgrgid(3) fails on your setup.

To test this compile this program (getgrgid_test.c) with "make getgrgid_test":

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

int
main(int argc, char **argv)
{
    int gid;
    struct group *g;

    if (argc != 2) {
        fprintf(stderr, "Invalid number of positional arguments\n");
        fprintf(stderr, "Usage getgrid_test GID\n");
        return 1;
    }
    gid = atoi(argv[1]);
    g = getgrgid(gid);
    if (g == NULL) {
        fprintf(stderr, "gid %d not found\n", gid);
        return 1;
    }
    printf("%s\n", g->gr_name);
    return 0;
}

Then run it with your gid like this:

getgrgid_test GID

If it doesn't produce a group name report to your system administrators.

Otherwise, if it does work, but "getent group GID" doesn't, it's a bug in "getent".

查看更多
登录 后发表回答