Get all user groups linux

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

    Tutorial details
    Difficulty level Easy
    Root privileges Yes
    Requirements None
    Est. reading time 1m
  1. /etc/group file – User group file
  2. members command – List members of a group
  3. lid command (or libuser-lid on newer Linux distros) – List user’s groups or group’s users

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.

Спасибо!
И поправьте, если я что-то не правильно сказал.

Источник

How to List All User Groups on Ubuntu 18.04 | 16.04 with Examples

This brief tutorial shows students and new users how to list groups on Ubuntu 18.04 | 16.04 Linux systems.

If you’re a student or new user looking for a Linux system to start learning on, the easiest place to start is on Ubuntu Linux OS. It’s a great Linux operating system for beginners.

Ubuntu is an open source Linux operating systems that runs on desktops, laptops, server and other devices.

Students and new users will find that Linux isn’t so different than Windows and other operating systems in so many ways, especially when it comes to use the system to get work done.…

Both Ubuntu and Windows systems allow you to be productive, easy to use, reliable and enable you to install and run thousands of programs from gaming to productivity suite software for individuals and businesses.

However, when you’re learning to use and understand Ubuntu Linux, you should also learn how to use the command line to terminal. Most Linux users can do some basic command line tasks. This tutorial is going to show you how..

This post shows you how to perform a basic task of listing groups on Ubuntu Linux.

When you’re ready to learn how to list groups on Ubuntu, follow the steps below:

Linux Groups:

There are two types of groups users can be assigned to: One is a primary and the other a secondary group which grants privileges to user to access certain resources.

Below is how a typical Linux user account is added and assigned group memberships:

User — A user has an account must belong to one primary group. Typically the the user’s primary group is also named after the user account name.
Primary Group — The primary group is created at the same time the user account is created and the user is automatically added to it. File created by the user automatically belongs to the user group.
Secondary Group — This group is not required and only there to give users access to other resources they’re don’t already have access to. Users can belong to none or as many secondary groups are possible.

The primary user’s group is stored in the /etc/passwd file and the supplementary groups, if any, are listed in the /etc/group file.

List User Groups using groups command

Now that you know the types of groups for users, you can use the groups command to find the groups a user belongs to. Running the groups command without any arguments, will list all the groups the user belongs to.

Should output all the group the account richard belongs to. The first group with same name as the user account name is the primary group.

To list all the groups a user belongs, add the username to the groups command

This should output same as above

List User Groups using the id command

One can also use the id command to list groups information about specified user. It prints user and group information for the specified USER,

The command will show the username (uid), the user’s primary group (gid), and the user’s secondary groups (groups)

Should output the line below:

List Group Membership using the getent command

If you want to know who are members of a particular group, use the getent command. This command gets entries from administrative database.

To get a membership of the cdrom group, run the command below

getent group cdrom

This should output all the users who have access to the cdrom group.

Listing All Groups

To list the entire groups on Ubuntu, run the command below

That should output all the groups on each line

Congratulations! You have learned how to list groups on Ubuntu Linux.

Источник

Читайте также:  What is clustering in windows server 2012
Оцените статью