How to add linux users to groups

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

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

Читайте также:  Работает ли trim 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.

Источник

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

Linux add user to group or remove user from group

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 «

# getent group admin admin:x:1003:

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

Verify the primary group of user1

# id user1 uid=1003(user1) gid=1003(admin) groups=1003(admin)

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)

I have below list of groups on my Linux server

# egrep 'admin|devops|qa_team' /etc/group admin:x:1003: devops:x:1004: qa_team:x:1005:

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

# useradd -G admin,devops,qa_team user2

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

# id user2 uid=1003(user2) gid=1006(user2) groups=1006(user2),1003(admin),1004(devops),1005(qa_team)

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

# useradd -g admin -G devops,qa_team user3

Verify the new user group details

# id user3 uid=1003(user3) gid=1003(admin) groups=1003(admin),1004(devops),1005(qa_team)

4. Change primary group of existing user

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

# id user4 uid=1004(user4) gid=1006(user4) groups=1006(user4)

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

Читайте также:  Linux mint установить пароль root

Verify the new primary group for user4

# id user4 uid=1004(user4) gid=1003(admin) groups=1003(admin)

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

# id user4 uid=1004(user4) gid=1003(admin) groups=1003(admin),1004(devops)

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 )

# usermod -G devops,qa_team user4
# id user4 uid=1004(user4) gid=1003(admin) groups=1003(admin),1004(devops),1005(qa_team)

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

# id user4 uid=1004(user4) gid=1006(user4) groups=1006(user4),1004(devops)

Alternatively you can also user gpasswd -a

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

# gpasswd -a user4 qa_team Adding user user4 to group qa_team
# id user4 uid=1004(user4) gid=1006(user4) groups=1006(user4),1005(qa_team)

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

# egrep admin /etc/group admin:x:1003:

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

# gpasswd -M user1,user2,user3 admin

Verify the admin group details

# egrep admin /etc/group admin:x:1003:user1,user2,user3

9. Remove user from Group (Supplementary or Secondary)

Currently my user4 is part of three different supplementary groups

# id user4 uid=1004(user4) gid=1006(user4) groups=1006(user4),1003(admin),1004(devops),1005(qa_team)

gpasswd is the best tool to remove user4 from qa_team group

# gpasswd -d user4 qa_team Removing user user4 from group qa_team

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 )

# usermod -G devops,admin user4
# id user4 uid=1004(user4) gid=1006(user4) groups=1006(user4),1003(admin),1004(devops)

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

# egrep admin /etc/group admin:x:1003:user1,user2,user3

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

remove user from 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

# groups user4 user4 : user4 admin devops qa_team

To remove user from all supplementary groups, use:

# id user4 uid=1004(user4) gid=1006(user4) groups=1006(user4)
# groups user4 user4 : user4

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.

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!!

Источник

How to Add or Remove Linux User From Group

Linux is by default a multi-user system (meaning many users can connect to it simultaneously and work), thus Linux user management is one of the fundamental tasks of a system administrator, which includes everything from creating, updating, and deleting user accounts or user groups on a Linux system.

In this short quick article, you will learn how to add or remove a user from a group in a Linux system.

Check a User Group in Linux

To find out what group a user is in, just run the following groups command and provide the username (tecmint in this example) as an argument.

# groups tecmint tecmint : tecmint wheel 

To find out the group of root user in Linux, just run the groups command without any argument.

# group root 

Check a User Group in Linux

Add a User to a Group in Linux

Before trying to add a user to a group, ensure that the user exists on the system. To add a user to a certain group, use the usermod command with the -a flag which tells the usermod to add a user to the supplementary group(s), and the -G option specifies the actual groups in the following format.

In this example, tecmint is the username and postgres is the group name:

# usermod -aG postgres tecmint # groups tecmint

Add User to Group in Linux

Remove a User from a Group in Linux

To remove a user from a group, use the gpasswd command with the -d option as follows.

# gpasswd -d tecmint postgres # groups tecmint

Remove User from Group in Linux

Additionally, on Ubuntu and its derivatives, you can remove a user from a specific group using the deluser command as follows (where tecmint is the username and postgres is the group name).

$ sudo deluser tecmint postgres

For more information, see the man pages for each of the different commands we have used in this article.

$ man groups $ man usermod $ man gpasswd $ man deluser

You will also find the following user management guides very useful:

Источник

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