Adding user to wheel group linux

Как добавить пользователя в группу Linux

Операционная система Linux изначально планировалась как многопользовательская система. Для управления правами доступа для каждого из пользователей используется три флага: чтение, запись и выполнение. Но этого было недостаточно, поэтому были придуманы группы пользователей Linux. С помощью групп можно дать нескольким пользователям доступ к одному ресурсу.

Файлу присваивается группа, для нее описываются права, затем в эту группу вступают пользователи, чтобы получить доступ к файлу. Читайте подробнее про все это в статье группы Linux. А в этой статье мы рассмотрим как добавить пользователя в группу linux.

Как добавить пользователя в группу Linux

Как я уже сказал, для каждого пользователя существует два типа групп, это первичная, основная для него группа и дополнительные.

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

Как обычно, лучше всего будет добавлять пользователя в группу через терминал, поскольку это даст вам больше гибкости и возможностей. Для изменения параметров пользователя используется команда usermod. Рассмотрим ее опции и синтаксис:

$ usermod опции синтаксис

Здесь нас будут интересовать только несколько опций с помощью которых можно добавить пользователя в группу root linux. Вот они:

  • -G — дополнительные группы для пользователя;
  • -a — добавить пользователя в дополнительные группы из параметра -G, а не заменять им текущее значение;
  • -g — установить новую основную группу для пользователя, такая группа уже должна существовать, и все файлы в домашнем каталоге теперь будут принадлежать именно этой группе.

У команды намного больше опций, но нам понадобятся только эти для решения нашей задачи. Теперь рассмотрим несколько примеров. Например, чтобы добавить пользователя в группу sudo linux используйте такую комбинацию:

sudo usermod -a -G wheel user

Если вы не будете использовать опцию -a, и укажите только -G, то утилита затрет все группы, которые были заданы ранее, что может вызвать серьезные проблемы. Например, вы хотите добавить пользователя в группу disk и стираете wheel, тогда вы больше не сможете пользоваться правами суперпользователя и вам придется сбрасывать пароль. Теперь смотрим информацию о пользователе:

Читайте также:  Драйвера амд для linux

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

sudo usermod -a -G disks,vboxusers user

Основная группа пользователя соответствует его имени, но мы можем изменить ее на другую, например users:

sudo usermod -g users user

Теперь основная группа была изменена. Точно такие же опции вы можете использовать для добавления пользователя в группу sudo linux во время его создания с помощью команды useradd.

Добавление пользователя в группу через GUI

В графическом интерфейсе все немного сложнее. В KDE добавление пользователя в группу linux выполняется с помощью утилиты Kuser. Мы не будем ее рассматривать. В Gnome 3 возможность управления группами была удалена, но в разных системах существуют свои утилиты для решения такой задачи, например, это system-config-users в CentOS и Users & Groups в Ubuntu.

Для установки инструмента в CentOS выполните:

sudo yum install system-config-users

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

Выполните двойной клик по имени пользователя, затем перейдите на вкладку «группы». Здесь вы можете выбрать отметить галочками нужные дополнительные группы, а также изменить основную группу:

Для установки утилиты в Ubuntu запустите такую команду:

sudo apt install gnome-system-tools

Здесь интерфейс будет немного отличаться, утилита будет выглядеть так же, как и системная программа настройки пользователей только появится возможность управления группами Linux.

Выводы

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

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

Источник

Learn Linux wheel group usage [With Examples]

Operating systems have a user with full privileges. However, since this user cannot be shared with the people logged into that system, they temporarily share some of their privileges with other users.
On Linux systems, the root user is the most authorized user. There is the sudo/wheel group for other users to use some of the privileges.
This group, which is called sudo in Debian based systems, is called wheel in Redhat and Arch base systems.

Читайте также:  Export http proxy linux

Users are taken to this group and authorized.

Confirm that you have the root user password before intervening in the wheel group. You may lose your authorization after an incorrect operation. We recommend that you perform these authorization processes with the root user.

Configuring Wheel Group in sudoers File

In the sudoers file, the wheel group is disabled in many Linux distributions. Even if the user is in this group, the following warning appears when he wants to perform an authorized transaction:

foc@fedora:~$ sudo cat /etc/sudoers | grep wheel [sudo] password for foc: foc is not in the sudoers file. This incident will be reported.
## Allows people in group wheel to run all commands # %wheel ALL=(ALL) ALL ## Same thing without a password # %wheel ALL=(ALL) NOPASSWD: ALL

This issue is resolved by removing the # sign at the beginning of the %wheel lines. Users who are in the wheel group in the first wheel line can run all commands with their own passwords. In the second wheel line, users do not need to enter a password:

#%wheel ALL=(ALL) NOPASSWD: ALL

Opening this line is not recommended for security reasons.

It can open the sudoers file with an editor(vi,nano etc):

[root@fedora faruk]# nano /etc/sudoers

or you can use visudo command:

Open the first line in the sudoers file and try the same action again:

wheel group

foc@fedora:~$ sudo cat /etc/sudoers | grep wheel ## Allows people in group wheel to run all commands %wheel ALL=(ALL) ALL # %wheel ALL=(ALL) NOPASSWD: ALL

Prevent wheel group users from changing root password

Wheel group users get root privileges temporarily. This authorization includes changing the root password. To prevent this, the sudoers file should be written like this:

%wheel ALL=(ALL) ALL, !/usr/bin/passwd root

After this operation, the user cannot change the root password even if user is in the wheel group:

faruk@fedora:~$ sudo passwd root Sorry, user faruk is not allowed to execute '/usr/bin/passwd root' as root on fedora.

Wheel Group Operations for Users

There are 2 methods to add/remove users to the wheel group. One is to use a command for this job, and the other is to manually edit the /etc/group file.

Add/Remove Users to the wheel group by editing the group file

Edit the /etc/groups file with a text editor (vim, nano etc) in the terminal:

Learn Linux wheel group usage [With Examples]

Type users in the wheel group line, one after the other, with a comma(«,») between them.

Читайте также:  Обновить время в линукс

Then, type sudo at the beginning of the commands you will type in the terminal to perform authorized action with the user. After the user enters his password, the action will take place:

[user1@fedora ]$ sudo cat /etc/sudoers [sudo] password for user1: ## Sudoers allows particular users to run various commands as ## the root user, without needing the root password. . 

To remove the user from the group, it is sufficient to delete the user from the wheel group line again. This step will prevent that user from taking authorized actions.

Add/Remove User from Wheel Group with Command

You have many alternatives for adding/removing users to the wheel group in Linux. When creating the user, you can create it by adding it to the wheel group with the adduser command:

[root@fedora faruk]# adduser user2 -G wheel

The added user is in the wheel group:

[root@fedora faruk]# cat /etc/group | grep wheel wheel:x:10:foc,faruk,user1,user2
[root@fedora faruk]# groups user2 user2 : user2 wheel

If the user is already added and you just want to put them in the wheel group, use the usermod command:

[root@fedora faruk]# usermod -aG wheel omer

The user is also included in the wheel group like this:

[root@fedora faruk]# cat /etc/group | grep wheel wheel:x:10:foc,faruk,user1,user2,omer

To remove the user from the wheel group, use the gpasswd command:

[root@fedora faruk]# gpasswd -d user1 wheel Removing user user1 from group wheel

This way user user1 is removed from wheel group:

[root@fedora faruk]# cat /etc/group | grep wheel wheel:x:10:foc,faruk,user2,omer

What you should do NEXT?

Summary

As we mentioned above, wheel group users are the most authorized users after root user. Care should be taken when adding/removing a user from this group.
Before adding/removing the wheel group, it should be ensured that the root password is known or you should switch to root user by logging in with an authorized user in a different terminal. Otherwise, you may lose all your privileges in that system.

In our article, we gave information about wheel, which is the super user authorization group in Linux.

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.

Thank You for your support!!

Источник

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