В этой статье мы рассмотрим различные способы представления членов группы в Linux.
В текстовом файле /etc/group хранится информация о группах.
В каждой строке содержится одна запись, содержащая следующую информацию:
- Название группы
- пароль
- Идентификатор группы (GID)
- Список пользователей группы
Чтобы получить представление о том, о чем мы говорим, мы собираемся создать новых пользователей, а затем добавлять их в группу с именем opensource.
Добавление нового пользователя
Чтобы добавить новый пользовательский запустите:
# adduser
You'll be prompted to enter the usernanme passsword and other details such as Phone number. For instance , let's add a new user called Andrew
addser andrew Adding user `andrew' ... Adding new group `andrew' (1001) ... Adding new user `andrew' (1004) with group `andrew' ... Creating home directory `/home/andrew' ... Copying files from `/etc/skel' ... Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully Changing the user information for andrew Enter the new value, or press ENTER for the default Full Name []: andrew james Room Number []: 45 Work Phone []: 555-456 Home Phone []: 987-764 Other []: Is the information correct? [Y/n] Y
Используя ту же команду и процедуру, мы можем добавить больше пользователей, в этом случае, Джеймса, Алиса и Пауля.
Добавление новой группы
Чтобы добавить новую группу, выполните:
# groupadd
Мы добавим новую группу с именем opensource
# groupadd opensource
Чтобы подтвердить, что группа существует в /etc/group запустите:
Добавление пользователей в группу
Теперь добавим вновь созданных пользователей в группу opensource. Синтаксис для этого следующий:
# usermod -aG
В нашем случае, чтобы добавить пользователей в нашу группу, мы запустим приведенную ниже команду и повторим ее для других пользователей:
# usermod -aG opensource james
Как перечислить членов группы
1) Использование cat /etc/group
Как мы видели ранее, информация о группе хранится в /etc/group.
# cat /etc/group
Вы получите список системных групп и группу, которую мы создали ранее
# opensource:x:1005:james,alice,paul
2) Использование команды members
Вы можете использовать команду members для перечисления пользователей в группе. Синтаксис для этого следующий:
# members groupname
В нашем случае:
members opensource
Вывод:
james alice paul
3) Использование команды getent
Вы также можете использовать команду getent для перечисления пользователей в группе, как показано ниже:
# getent group groupname
Пример:
# getent group opensource
Вывод:
opensource:x:1005:james,paul
4) Использование скрипта perl
Наконец, вы можете перечислить все группы в вашей системе Linux и отобразить все элементы в этих группах, используя скрипт perl, как показано далее.
Сначала создайте скрипт, используя ваш любимый текстовый редактор
# vim userlist.pl
Скопируйте текст ниже и сохраните файл:
#!/usr/bin/perl -T # # Lists members of all groups, or optionally just the group # specified on the command line. use strict; use warnings; $ENV{"PATH"} = "/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{$group}->{$userid} = 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{$group}}) { print $member,"\n"; } }
Разрешите выполнение скрипта:
# chmod +x userlist.pl
И, наконец запустите его:
# chmod +x userlist.pl
Пример вывода:
Group opensource has the following members: james paul Group paul has the following members: paul Group plugdev has the following members: ubuntu Group postfix has the following members: postfix Group proxy has the following members: proxy Group root has the following members: root Group sudo has the following members: ubuntu Group sys has the following members: sys Group syslog has the following members: syslog Group systemd-bus-proxy has the following members: systemd-bus-proxy Group systemd-network has the following members: systemd-network Group systemd-resolve has the following members: systemd-resolve Group systemd-timesync has the following members: systemd-timesync Group ubuntu has the following members: ubuntu Group uucp has the following members: uucp Group uuidd has the following members: uuidd Group video has the following members: ubuntu Group www-data has the following members: www-data