Перейти к содержимому

Ubuntu как узнать группу пользователя

  • автор:

Как вывести список групп в Linux

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

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

Группы Linux

Пользователь может принадлежать к двум типам групп:

Первичная группа или группа входа в систему — это группа, которая назначается файлам, создаваемым пользователем. Обычно имя основной группы совпадает с именем пользователя. Каждый пользователь должен принадлежать ровно к одной основной группе.

Вторичная или дополнительная группа — используется для предоставления определенных привилегий набору пользователей. Пользователь может быть участником нуля или нескольких вторичных групп.

Список всех групп, членом которых является пользователь

Есть несколько способов узнать, к каким группам принадлежит пользователь.

Основная группа пользователей хранится в /etc/passwd а дополнительные группы, если таковые имеются, перечислены в /etc/group .

Один из способов найти группы пользователей — перечислить содержимое этих файлов с помощью cat , less или grep . Другой более простой вариант — использовать команду, цель которой — предоставить информацию о пользователях и группах системы.

Использование команды groups

Самая запоминающаяся команда для вывода списка всех групп, членом которых является пользователь, — это команда groups . При выполнении без аргумента команда распечатает список всех групп, к которым принадлежит текущий зарегистрированный пользователь:

Первая группа — это основная группа.

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

Как и раньше, первая группа является первичной.

Используя команду id

Команда id выводит информацию об указанном пользователе и его группах. Если имя пользователя не указано, отображается информация для текущего пользователя.

Например, чтобы получить информацию о пользователе linuxize вы должны ввести:

Команда покажет идентификатор пользователя ( uid ), основную группу пользователя ( gid ) и вторичные группы ( groups ) пользователя.

Чтобы напечатать только имена вместо чисел, используйте параметр -n . Опция -g выведет только основную группу и -G все группы.

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

Список всех участников группы

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

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

Если группа существует, команда напечатает группу и всех ее членов:

Если нет вывода, это означает, что группа не существует.

Список всех групп

Чтобы просмотреть все группы, присутствующие в системе, просто откройте файл /etc/group . Каждая строка в этом файле представляет информацию для одной группы.

Другой вариант — использовать команду getent которая отображает записи из баз данных, настроенных в файле /etc/nsswitch.conf включая базу данных group которую мы можем использовать для запроса списка всех групп.

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

Вывод такой же, как при отображении содержимого файла /etc/group . Если вы используете LDAP для аутентификации пользователя, getent отобразит все группы как из файла /etc/group и из базы данных LDAP.

Вы также можете использовать awk или cut для печати только первого поля, содержащего имя группы:

Выводы

В этом руководстве вы узнали, как найти группы, членом которых является пользователь. Те же команды применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.

How to find out what group a given user has?

In Unix/Linux, how do you find out what group a given user is in via command line?

niton's user avatar

5 Answers 5

This one shows the user’s uid as well as all the groups (with their gids) they belong to

On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:

which is equivalent to groups [user] utility which has been obsoleted on Unix.

On OS X/Unix, the command id -p [user] is suggested for normal interactive.

Explanation on the parameters:

-G , —groups — print all group IDs

-n , —name — print a name instead of a number, for -ugG

-p — Make the output human-readable.

7 methods to list user groups in Linux? [SOLVED]

In operating systems, applications add their own users and groups to the system. From an administrative point of view, this makes it easier for users. Adding users to the application group is the easiest way to edit privileges. As a matter of fact, systems such as LDAP and Active Directory are also built on this method.

There are many methods of listing groups in Linux. In some methods, group information is accessed from the user, while in some methods, users are accessed from group information. We will tell you some of the most used methods with examples.

Method-1: Using groups command

When you run the groups command without any parameters, it lists the group information of the user who opened the terminal:

If you type a username after the group command, the groups belonging to that user are listed:

In this method, groups are listed with user information.

Method-2: Using id command

Like the group command, the id command, when executed without parameters, lists the active user’s groups. But this time group id are also displayed:

By typing the username after the id command, the groups belonging to that user are listed with their ids:

As the user’s group information increases, the information displayed on the screen may not be understood. With the parameters of the ID command, the output can be made more understandable. For example, to list all group ids and names:

You can get help from the —help page for all its parameters:

Again in this method, groups are listed with their user information.

Method-3: Using getent command

The getent command pulls information from the group database. If there is no central system such as LDAP, Active Directory, it will pull from the local database.

You can pull groups by typing group after getent command:

To list users in a group, you must type the group name:

To list all groups in the system without details:

This method lists both groups and users in that group.

Method-4: Using /etc/group file

On Linux the group information is in the /etc/group file. If a user is added or removed from the group, this file changes.

When you view this file with file view commands like cat , it gives a complex output. To list group information, you can write it like this:

For the total number of groups:

Using awk command we can extract the group names from the /etc/group file using the colon ( : ) delimiter.

Method-5: Using compgen command

Another command you can use to list groups in Linux is compgen . You can list the groups in the system with the -g parameter:

Method-6: Using lid command

This command displays information about the specified group, including the GID, group password (if any), and members.

Method-7: Using dscl command (On MacOS)

Using the dscl command on macOS. This command displays information about the specified group on macOS.

Bonus Tip

If you want to list the groups of users logged into the system, you can use the following for loop:

Note: Bash was chosen as the default shell. If a different shell(zsh,sh etc) is used, it can be written after the grep command.

What is NEXT?

Summary

There is always an alternative on Linux. We have explained different ways to list groups in Linux for you. The commands and methods used may vary according to habits. You can use whichever method is faster and easier for you. Of course the choice is yours.

You can get help with the -h/—help parameter for each command. For more detailed information, you can also access the man page of the commands as in the example:

References

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

List Groups in Ubuntu Command Line

Sagar Sharma

Ezoic

report this ad

Linux, from its core, is built to have multiple users.

And separating users into different groups is pretty convenient for managing permissions.

A user can be a member of more than one group. This is why the groups are divided into the following two categories:

Please enable JavaScript

  • Primary group : Also known as the login or default group. If the user creates a file, the primary group takes the group ownership. Usually, the primary group has the same name as the user.
  • Secondary group : Also known as a supplementary group. It is used to grant specific permissions to users. For example, in Ubuntu, only members of the sudo groups can run commands with sudo.

How do you know which group a user belongs to? Let me show you that.

How to check the groups of a user

Here are various scenarios for listing user groups in Ubuntu.

List groups of the current user

To list the groups of the current user, all you have to do is execute a single command without any additional flags:

list groups of the curent user

Yep, all you have to do is execute the groups command!

List groups of the other users

If you want to find out the groups to which the specific user belongs, all you have to do is append the username to the groups command:

For your reference, here, I checked the groups where the user root and sagar belong:

list groups of the specific user

I could have used both users in single command as well.

List all the groups in Ubuntu

You just learned how to see which groups a user belongs to. How about listing all the available groups? That can be done too.

The /etc/group file contains all the necessary information about the local group.

So you can read the contents of that file and easily list the groups:

use groups file to list groups in ubuntu

Similarly, if you want to find a specific group, you can use the grep command to filter the output:

find speciofic group in linux

In case you are wondering about the meaning of the output, here's what that means:

  • sudo is the name of the group.
  • x indicates that shadow passwords are being used and can be found at /etc/gshadow .
  • 27 is the group ID.
  • sagar is the list of the group users. You can have multiple of them.

And if they seem irrelevant, you can use the cut command and print the group names only:

use the cut command to trim output in ubuntu terminal

Another option is to use the getent command

How to list groups using the getent command

The getent command is used to get entries from the database, including passwd and group database.

This means it can be used for our purpose too!

To get a list of groups, all you need to do is append group to the getent command:

use getent command to list groups in ubuntu terminal

List every member of a specific group

If you want a list of every user belonging to a specific group, you can use the getent command in the following syntax:

Let's say I want to list every member of the sudo group, then I will be using the following command:

list each member of user group in ubuntu

Want to know how you can add a user to a group?

Cannot see the group you are looking for? How about creating that group?

Learn Ubuntu Sagar Sharma

If you want to add a user to an existing group and have no idea how to? We have a dedicated guide to solve this issue:

Learn Ubuntu Abhishek

I hope you will find this guide helpful and if you have any queries, let me know in the comments.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *