- How To List All Users and Groups in Linux
- Print User File Named passwd
- Print Only Usernames
- Print Users Who Have Login
- Print Users Who Have Home Directories
- Print Group File
- Print Only Group Names
- Linux Show The Groups a User Is In
- Example
- How Do I Find Out My Primary Group Membership?
- Linux Show All Members of a Group Command
- Linux Show All Members of a Group Commands
- Linux: List all members of a group using /etc/group file
- Display group memberships for each Linux user
- Linux List all members of a group using members command
- How to list all users in a Linux group using lid command
- To see users contained in group named ‘ftponly’:
- To show information about groups containing user named ‘nixcraft’:
- How to list groups in Linux
- Conclusion
- Список пользователей группы в Linux
- Список пользователей группы в Linux
- 1. Файл /etc/group
- 2. Команда members
- 3. Команда lid
- Выводы
- Оцените статью:
- Об авторе
- 4 комментария
How To List All Users and Groups in Linux
Users and group files are important for Linux. Normal users will interact with Linux systems by using credentials provided in the user ad group file.
Print User File Named passwd
We can get content of the user file like below. This file provides usernames home directories and shell information.
Print User File Named passwd
As we can see each line of the output provides the user name, user id, user group, user shell, user home path etc.
Print Only Usernames
We can print only usernames by filtering other columns like below.
Print Only Usernames
Print Users Who Have Login
By default normal users will login to the Linux box. But in some cases service users do not need to login Linux system. This is also a security measure. We can list users who do not have login right with the following command. This login information is stored in the /etc/passwd file.
Print Users Who Have Login
Print Users Who Have Home Directories
We can print only users who have home directories in /home. This command will first look in to the passwd to list users how have /home and then print only user names from result.
Print Users Who Have Home Directories
Print Group File
Linux users have primary and secondary groups. These group names are stored in the /etc/group file. We can print this group information and assigned user with cat command. For more details read following tutorial.
Print Only Group Names
We can print only group names by cutting other column like below.
Print Only Group Names
Источник
Linux Show The Groups a User Is In
Example
pen a command-line terminal (select Applications > Accessories > Terminal), and then type:
$ groups
Sample outputs:
You are part of all of the above groups. To find group memebership for root user, enter:
$ groups root
Sample outputs:
Please note that (from the groups man page):
Primary and supplementary groups for a process are normally inherited from its parent and are usually unchanged since login. This means that if you change the group database after logging in, groups will not reflect your changes within your existing login session. Running `groups’ with a list of users causes the user and group database to be consulted afresh, and so will give a different result.
You can also use the id command as follows to get the same information:
$ id -Gn
$ id -Gn userName
$ id -Gn vivek
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How Do I Find Out My Primary Group Membership?
Type the following command:
$ getent group userName
$ getent group vivek
Sample outputs:
In this example, user vivek has group id # 1000 and has group name vivek for primary group membership.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Linux Show All Members of a Group Command
Linux Show All Members of a Group Commands
- /etc/group file – User group file
- members command – List members of a group
- lid command (or libuser-lid on newer Linux distros) – List user’s groups or group’s users
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | None |
Est. reading time | 1m |
There are two types of groups in Linux:
- Primary group – is the main group that is associated with user account. Each user is a member of exactly one primary group.
- Secondary group – used to provide additional rights to user. For example, access to the dvd/cdrom drive can be granted with help of cdrom group.
Linux: List all members of a group using /etc/group file
Use the grep command or cat command/more command as follows:
$ grep ‘grpup-name-here’ /etc/group
$ grep ‘ftponly’ /etc/group
$ cat /etc/group
$ less /etc/group
$ grep -i —color ‘ftponly’ /etc/group
We can also type the compgen command or getend command to list all group names on Linux:
$ compgen -g
$ getent group
To get just a list of all members of a group called ftponly , type the following awk command:
Display group memberships for each Linux user
Want to see group memberships for each given USERNAME under Linux? The syntax is as follows for the groups command:
groups
groups
groups vivek
The following outputs indicates that the user named ‘vivek’ is part of four groups including ‘vivek’ primary group:
Linux List all members of a group using members command
Warning: members command is not installed on most Linux distros. Use yum command or apt-get command/apt command to install the same:
$ sudo apt-get install members
To outputs members of a group called ftponly, enter:
$ members
$ members ftponly
Fig. 01: members command in action to list members in a group
How to list all users in a Linux group using lid command
You can displays information about groups containing user name, or users contained in group name using lid command as follows.
Warning: lid command is not installed on most distros. Use yum command or apt-get command to install the same:
$ sudo apt-get install libuser
To see users contained in group named ‘ftponly’:
# lid -g ftponly
Please note that newer version of libuser renamed the lid command to libuser-lid . Thus, use it as follows:
$ sudo libuser-lid -g ftponly
Sample outputs:
To show information about groups containing user named ‘nixcraft’:
Use lid command or libuser-lid command on Linux to show all members of a group named nixcraft:
# lid nixcraft
OR
$ sudo libuser-lid nixcraft
Sample outputs:
See lid command man page for more information.
How to list groups in Linux
To see all users, run less command/more command:
less /etc/group
OR
more /etc/group
Another option is to type the following getent command:
getent group
For example, locate the members of a group with the name vboxusers, run:
getent group vboxusers
Sample outputs indicating vivek and raj users are part of vboxusers group:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Finally, you can use the id command to display real and effective user and group IDs:
id
id vivek
id -nG raj # show all group IDs for raj user
id -ng raj # show only effective group ID for raj user
Conclusion
Now you know how to use various Linux commands to show all members of a group. I suggest you read the man pages for more info by typing the following man command:
$ man libuser-lid
$ man members
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Список пользователей группы в 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 она поставляется по умолчанию. Если в вашем дистрибутиве её нет, то вы можете установить её из официальных репозиториев:
sudo apt install members
Для других дистрибутивов будут отличаться только пакетные менеджеры, пакет утилиты называется так же. Для работы утилите надо передать только имя группы:
$ members опции имя_группы
В качестве пользователей можно передать:
- —all — все пользователи группы;
- —primary — только те пользователи, для которых эта группа является основной;
- —secondary — только те пользователи, для которых эта группа является дополнительной;
- two-lines — отобразить пользователей, для которых данная группа является основной и тех для кого она установлена в качестве дополнительной.
Например, посмотрим пользователей группы adm:
Или посмотрим пользователей, которые выбрали группу adm в качестве основной:
members —primary adm
Как видите, таких пользователей нет, а те, которых мы видели раньше, используют эту группу в качестве дополнительной:
members —secondary adm
3. Команда lid
Команда lid тоже может отображать информацию о группах. Но перед тем, как вы сможете её использовать, её надо установить. Утилита входит в пакет libuser. В Ubuntu команда выглядит так:
sudo apt install libuser
Чтобы посмотреть пользователей группы, достаточно, как и в предыдущем варианте, передать утилите имя:
sudo libuser-lid -g adm
Опция -g обязательна. Если её не передать, утилита покажет список групп текущего пользователя. Если не передать имя группы, то утилита покажет список пользователей основной группы текущего пользователя.
Выводы
В этой небольшой статье мы рассмотрели, как управлять списком пользователей группы Linux. Как видите, здесь нет ничего сложного. Если у вас остались вопросы, спрашивайте в комментариях!
Оцените статью:
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
4 комментария
Если уж пользовать 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.
Спасибо!
И поправьте, если я что-то не правильно сказал.
Источник