Add user to all groups linux

10 practical examples to add or remove user from group in Linux

Table of Contents

In this article I will cover the below topics and share multiple practical examples cover these scenarios

  • Different types of group in Linux
  • Add user to group (single)
  • Add user to multiple groups
  • Change primary group of the user
  • Remove user from group

So when you say Linux add user to group, which group do you mean? There are two types of group in Linux

  • Primary Group
  • Supplementary or Secondary Group

Difference between Primary vs Supplementary Group

Primary group:

  • The group that is listed in the group membership field for a user in /etc/passwd .

For example here deepak is part of primary group with GID 1000 i.e. deepak (so primary group name is same as loginname)

  • When we create user using useradd , depending upon USERGROUPS_ENAB variable in /etc/login.defs a primary group is created/assigned to user. If this variable is set to yes, a group will be created for the user, with the same name as her loginname . If the variable is set to no, useradd will set the primary group of the new user to the value specified by the GROUP variable in /etc/default/useradd , or 100 by default
  • On Linux, every file and directory has a user owner and a group owner. Group ownership is set when files are created, and unless configured otherwise, it is set to the primary group of the user who creates the file.
  • A user at a time can be part of only one primary group.

Supplementary (or Secondary) Group:

  • A user can be part of multiple supplementary group
  • A group that a user is a member of but which membership is not defined in the /etc/passwd file.
  • When creating new files, the supplementary group will not automatically become the owner of those files.

1. Create a new user and add to existing primary group

  • By default when we create a new user, a new primary group is created by the same name as of the user.
  • But we can also use useradd to create a user and add this user to any existing group
  • So this group will not become the primary group of your new user

In this example I will create a new group » admin «

Verify the group exists

Next I will create a new user » user1 » and add this user to » admin » group using useradd -g

Verify the primary group of user1

2. Create a new user and add to existing supplementary group

We want to create a new user and add him/her to supplementary group (please NOTE, we will add the user to supplementary group and not the primary group here)

Читайте также:  Linux автоматическое монтирование дисков при загрузке

I have below list of groups on my Linux server

I will create a new user » user2 » and add this user to all these supplementary groups using useradd -G , , ..

Verify the supplementary groups.

Please NOTE that since we did not specified primary group using -g , a new group user2 is created and assigned as primary group to the user

3. Create a new user and add to existing primary and supplementary group

Now we will combine both the above arguments i.e. -g to add primary_group and -G to add supplementary_group
In this example i will create user3 with primary_group as admin and with supplementary_group of devops and qa_team

Verify the new user group details

4. Change primary group of existing user

I have a user who is currently added to his own primary group

I will change the primary group of this user to admin using usermod

Verify the new primary group for user4

5. Add user to Group (Supplementary or Secondary) using usermod

  • To add user to group we can use use usermod or gpasswd command
  • We can add user to supplementary groups only
  • In this example I will add user4 to devops supplementary group

Syntax to add user to group: usermod -G

Verify the user details

6. Add user to multiple groups (Supplementary or Secondary) using usermod

We can also add user to multiple supplementary groups using syntax usermod -G , , ..
In this example I will add user4 to multiple supplementary groups ( devops and qa_team )

Verify the user details

7. Add user to Group (Supplementary or Secondary) using gpasswd

  • Similar to usermod we can also user gpasswd to add user to group
  • The syntax to add user to group is gpasswd -M

In this example I will add user4 to devops as supplementary group

Verify the user details

Alternatively you can also user gpasswd -a

In this example I will add user4 to qa_team as supplementary group

Verify the user details

8. Add multiple users to same group

We need to user gpasswd to add multiple users to same group
Currently I already have admin group which does not contain any users at the moment

The syntax to add multiple users to single group would be gpasswd -M , , ..

In this example I will add my existing users i.e. user1 , user2 and user3 to admin as supplementary group

Verify the admin group details

9. Remove user from Group (Supplementary or Secondary)

Currently my user4 is part of three different supplementary groups

gpasswd is the best tool to remove user4 from qa_team group

We can also use usermod command to remove user from group. The problem with usermod is that you must define the complete list of supplementary group which the user is part of and only remove the group which you wat to remove the user from.

For example, my user4 is part of devops , admin and qa_team . So to remove user4 from qa_team we will re-add user to group devops and admin (not to qa_team )

Verify the user details

I would recommend using gpasswd to remove user from group

10. Remove multiple users from supplementary group

There is no single command to remove multiple users from single group but we can use a small script
Currently I have admin which has three users

I will write a small script to remove all the 3 users from admin group

remove multiple users from same group

11. Remove user from all Groups (Supplementary or Secondary)

  • We can use gpasswd to remove user from group
  • But if a user is part of multiple groups then you need to execute gpasswd multiple times
  • Or write a script to remove user from all the supplementary groups
  • Alternatively we can use usermod -G «»

Currently my user4 is part of multiple supplementary groups

To remove user from all supplementary groups, use:

Читайте также:  Audio card driver windows

Verify the user details

Lastly I hope the steps from the article to add user to group, remove user from group and difference between primary group and supplementary group on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

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.

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

Thank You for your support!!

Источник

Как добавить пользователя в группу 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, тогда вы больше не сможете пользоваться правами суперпользователя и вам придется сбрасывать пароль. Теперь смотрим информацию о пользователе:

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

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

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

Читайте также:  Api ms win crt runtime l1 1 0 dll windows server 2012

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

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

sudo apt install gnome-system-tools

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

Выводы

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

Источник

Linux: Add User to Group

This tutorial shows you step by step how to add a user to a group on Linux with several examples using the Linux command-line. It also explains how to add users and groups on Linux. The commands should work on any Linux Distribution and have been tested on CentOS, Debian, and Ubuntu.

Add a new Linux User to a Group

A Linux user can have one primary group and one or more secondary groups. The groups can be set as parameters of the adduser command when you create the user.

All commands have to be executed as the root user. On Ubuntu, please prepend the word «sudo » to all commands or run «sudo -s» to become root user.

Add Linux Group

As a first step, I will add a new group named «family» and a second group «friends»:

Add User to Group

Then I will add a new user «tom» to our group «family». The family group will be added as a secondary group by using the -G parameter.

Add User to two groups

Tom is now a member of the family group. The -G parameter allows it to list several groups separated by a comma. To add the user tom into the family and friends group, use this command:

Set User password

Please note that our new Linux user tom has no password yet, so he can’t login. To set a password for this user, run:

And enter the new password twice when the command requests it.

In the above example, we added the user tom to a secondary group, the adduser command has created a new primary group with the name of the user automatically and assigned this group as a primary group.

  • Username: tom
  • Primary Group: tom
  • Secondary Group: family (or family + friends if you followed the second example)

Set new primary group

Maybe you want that tom gets family as his primary group and friends as his secondary group? Then use this command instead:

to create the user tom. the -g switch tells the useradd command to use family as the primary group. There is no group tom in this case.

Use the man (manpage) command to get a detailed description of all command-line options for useradd:

Add an existing Linux User to a Group

For this task, we will use the usermod command. Usermod allows it to modify various options of the user including the group memberships of the User.

First I will add a third group with the name colleagues.

Usermod command example

I will add the colleagues group as the secondary group to the user tom.

The command explained: The -a switch stands for «append«, it is used in combination with the -G switch (that stands for the secondary group) only. The result is that we add tom to the group colleagues and this group is an additional or secondary group for the user.

The -G option allows it to add several groups at once by listing the group names separated by a comma. e.g.: «-G group1,group2,group3».

To change the primary group of the user tom to family, run:

Use man (manpage) command to get a detailed description of all command-line options for usermod:

Источник

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