Get member of group linux

How to list all users in a Linux group?

I’m new here, I found out that SF exists right after I posted the question. I agree it belongs either to SF or SO.

20 Answers 20

It is portable across both Linux and Solaris, and it works with local group/password files, NIS, and LDAP configurations.

Unfortunately, there is no good, portable way to do this that I know of. If you attempt to parse /etc/group, as others are suggesting, you will miss users who have that group as their primary group and anyone who has been added to that group via a mechanism other than UNIX flat files (i.e. LDAP, NIS, pam-pgsql, etc.).

If I absolutely had to do this myself, I’d probably do it in reverse: use id to get the groups of every user on the system (which will pull all sources visible to NSS), and use Perl or something similar to maintain a hash table for each group discovered noting the membership of that user.

Edit: Of course, this leaves you with a similar problem: how to get a list of every user on the system. Since my location uses only flat files and LDAP, I can just get a list from both locations, but that may or may not be true for your environment.

Edit 2: Someone in passing reminded me that getent passwd will return a list of all users on the system including ones from LDAP/NIS/etc., but getent group still will still miss users that are members only via the default group entry, so that inspired me to write this quick hack.

 #!/usr/bin/perl -T # # Lists members of all groups, or optionally just the group # specified on the command line # # Copyright © 2010-2013 by Zed Pobre (zed@debian.org or zed@resonant.org) # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # use strict; use warnings; $ENV = "/usr/bin:/bin"; my $wantedgroup = shift; my %groupmembers; my $usertext = `getent passwd`; my @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm; foreach my $userid (@users) < my $usergrouptext = `id -Gn $userid`; my @grouplist = split(' ',$usergrouptext); foreach my $group (@grouplist) < $groupmembers-> = 1; > > if($wantedgroup) < print_group_members($wantedgroup); >else < foreach my $group (sort keys %groupmembers) < print "Group ",$group," has the following members:\n"; print_group_members($group); print "\n"; >> sub print_group_members < my ($group) = @_; return unless $group; foreach my $member (sort keys %<$groupmembers>) < print $member,"\n"; >> 

Источник

How to List the Members of a Group In Linux?

In Linux, a group is a unit that is useful to share files/directories within the local system or from the local to the remote system. It can contain multiple users that are known as its group members. Each group member has the same permissions and privileges that can be easily managed by using the right commands.

This post illustrates possible methods to list the members of a group in Linux having the following outcomes:

  • Method 1: Using the “getent” Command
  • Method 2: Using the “members” Command
  • Method 3: Using the “groupmems” Command
  • Method 4: Using the “libuser-lid” Command
  • Method 5: Using the “/etc/group” File

Method 1: Using the “getent” Command

The “getent” is a built-in Linux command to show the details of the database having entries “passwd”, “group”, “services”, “network”, and “protocols”. It is known as the common method to get user details in Linux.

The “getent” command displays the group databases configured in /etc/nsswitch.conf file.

Execute the “getent” command with the specified group to check its group members:

The output displays four entries in one line i.e group_nmae, password(encrypted), group_id, and group_list(group_member “itslinuxfoss”).

Here the “sudo” group member is only one “itslinuxfoss”.

Method 2: Using the “members” Command

As the “member” command name clearly tells that it is beneficial for listing the members of the group.

It is an external command so first install it in the Linux system as per distributions using default package managers:

$ sudo yum install members #For Fedora $ sudo dnf install members #For CentOS/RHEL $ sudo apt install members #For Ubuntu/Debian-Based

The “members” utility has been successfully installed in current Linux distro Ubuntu 22.04.

Simply enter the “member” command with the targeted group name to display its members’ list in this way:

It displayed only the group member “saned” of the “scanner” group.

Method 3: Using the “groupmems” Command

The “groupmems” is another command line tool that allows Linux users to manage their group membership without having superuser privileges.

However, it needs the superuser privileges to access the “/etc/gshadow” file for getting the group members by following the “-l(list)” flag alongside the group name:

$ sudo groupmems -g sambashare -l

The “sambashare” group is associated with the group member “itslinuxfoss”.

Method 4: Using the “libuser-lid” Command

Another external “lid” command is beneficial for getting group details. It is just like the “groupmems”, and the “members” command that displays members of a group in the Linux operating system.

Install the libuser Command Support

It is not pre-installed in the Linux operating system but can be easily installed using the below-mentioned commands:

$ sudo yum install libuser #For Fedora $ sudo dnf install libuser #For CentOS/RHEL $ sudo apt install libuser #For Ubuntu/Debian-Based

When the installation is completed, run “libuser-lid” with the “-g(group)” flag to get the group members of “adm” group with superuser privileges:

The output shows the “adm” group members list along with their IDs.

Method 5: Using the “/etc/group” File

The “/etc/group” is a text file that contains the user’s group information. It contains group information in four entities that are described here:

  • Group_name: Represents the user group name.
  • Password: Shows the encrypted password. It is usually blank in case of no password.
  • Group_ID: Identifies the group id.
  • Group List: Displays the group members separated by commas.

It generally displays all group details however to get the specified group members list use it with the “grep” command:

The user “itslinuxfoss” is a member of the “sudo” group.

Conclusion

Linux and its distributions offer the “getent”, “groupmems”, “members”, and “libuser_lid” command line utilities for listing the group members of a group. In addition, this task can also be performed by accessing the “/etc/group” file using the “cat(for all)”, and “grep(for particular)” commands. This guide has provided a detailed view to list the members of a group in Linux.

Источник

Список пользователей группы в Linux

Мы уже много раз на этом сайте говорили про группы пользователей в Linux. Это основной и очень удобный способ управления полномочиями пользователей и процессов в этой операционной системе. Список групп, мы знаем, как посмотреть, а что, если нужно узнать, какие пользователи имеют доступ к ресурсам одной из групп?

Посмотреть список пользователей группы в Linux достаточно просто, для этого существует несколько способов. И в этой статье мы их все рассмотрим.

Список пользователей группы в Linux

1. Файл /etc/group

Все группы, созданные в ОС Linux собраны в файле /etc/group. Синтаксис записи группы в этом файле следующий:

имя_группы :x: идентификатор : список_пользователей

  • имя_группы — имя, которое используется для управления группой и отображается в выводе команд;
  • x — заглушка для пароля;
  • идентификатор — уникальный идентификатор группы;
  • список_пользователей — все пользователи, которые входят в группу, разделённые запятой.

Таким образом, вы можете посмотреть список пользователей, просто отыскав группу в файле:

Или также можно воспользоваться регулярным выражением grep:

cat /etc/group | grep group7

Например, здесь в группу group7 входит только пользователь sergiy. А вот в группу adm входит sergiy и syslog:

2. Команда members

Следующий способ посмотреть пользователей группы — команда members, в Ubuntu она поставляется по умолчанию. Если в вашем дистрибутиве её нет, то вы можете установить её из официальных репозиториев:

Для других дистрибутивов будут отличаться только пакетные менеджеры, пакет утилиты называется так же. Для работы утилите надо передать только имя группы:

$ members опции имя_группы

В качестве пользователей можно передать:

  • —all — все пользователи группы;
  • —primary — только те пользователи, для которых эта группа является основной;
  • —secondary — только те пользователи, для которых эта группа является дополнительной;
  • two-lines — отобразить пользователей, для которых данная группа является основной и тех для кого она установлена в качестве дополнительной.

Например, посмотрим пользователей группы adm:

Или посмотрим пользователей, которые выбрали группу adm в качестве основной:

Как видите, таких пользователей нет, а те, которых мы видели раньше, используют эту группу в качестве дополнительной:

3. Команда lid

Команда lid тоже может отображать информацию о группах. Но перед тем, как вы сможете её использовать, её надо установить. Утилита входит в пакет libuser. В Ubuntu команда выглядит так:

Чтобы посмотреть пользователей группы, достаточно, как и в предыдущем варианте, передать утилите имя:

Опция -g обязательна. Если её не передать, утилита покажет список групп текущего пользователя. Если не передать имя группы, то утилита покажет список пользователей основной группы текущего пользователя.

Выводы

В этой небольшой статье мы рассмотрели, как управлять списком пользователей группы Linux. Как видите, здесь нет ничего сложного. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Похожие записи

Оцените статью

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

4 комментария к “Список пользователей группы в Linux”

Если уж пользовать grep, то во-первых, совершенно не обязательно отдавать поток cat-ом, потому что grep сам умеет читать текстовые файлы, и во-вторых, в регулярном выражении grep перед именем группы ставьте «морковку», тогда выхлоп будет более оптимальным. grep ^group_name /etc/group Таким образом вы избавитесь и от программного канала, и от лишних строк в выхлопе. Ответить

Чуток добавлю: Команда groups без параметров расскажет пользователю, в каких группах он состоит.
Команда groups alex расскажет, в каких группах состоит alex. В силу моей деятельности я часто встречаюсь со случаями, когда пользователи (конкретно — разработчики устройств на микроконтроллерах) не могут подключить какой своё устройство или программатор к компу. Нужно-то всего ничего! Нужно узнать, какую группу образует порт устройства и добавить пользователя (разработчика) в эту группу. Группу порта устройства можно узнать командой ls. Например, у нас есть железка на базе какого-нибудь микроконтроллера, которая подключается к компу посредством USB-порте. В железке используется микросхема конвертера USB/UART (типа FT232RL, CH340G, CP2103, . ) Всё вроде бы хорошо, но комповая программа не хочет соединяться с железкой. Тогда выполняем команду: $ ls -al /dev/ttyUSB0
crw-rw—- 1 root dialout 188, 0 окт 30 15:13 /dev/ttyUSB0 Здесь мы видим, что владельцем устройства является root, но устройство также входит в группу dialout. Теперь, чтобы получить доступ к устройству, нам (пользователю) нужно тоже входить в эту же группу. Выполняем команду: # adduser alex dialout # Команда выполняется из-под root-а. Затем заново входим в систему и с устройством можно работать. И если теперь выполнить команду groups, то можно заметить, что пользователь сейчас входит также и в группу dialout. Спасибо!
И поправьте, если я что-то не правильно сказал. Ответить

у меня ls -alF показывает владельцев каталогов и файлов 10668 (папка с JDK) нет такого пользователя и группы. Это нормально вообще? как мне быть теперь если я захочу OpenJDK? каких владельцев мне указывать с chown ? Ответить

Источник

Читайте также:  Команда линукс свернуть все окна
Оцените статью
Adblock
detector