Linux add user to the group

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:

Источник

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

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

Группы Linux

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

Читайте также:  Aimp для windows 4pda

В операционных системах Linux есть два типа групп:

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

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

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

Только root или пользователи с доступом sudo могут добавлять пользователя в группу.

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

Чтобы добавить существующего пользователя во вторичную группу, используйте команду usermod -a -G после имени группы и пользователя:

Например, чтобы добавить пользователя linuxize в группу sudo , вы должны выполнить следующую команду:

Всегда используйте параметр -a (добавить) при добавлении пользователя в новую группу. Если вы опустите опцию -a , пользователь будет удален из всех групп, не перечисленных после опции -G .

В случае успеха команда usermod не выводит никаких результатов. Он предупреждает вас только в том случае, если пользователь или группа не существует.

Как добавить существующего пользователя в несколько групп одной командой

Если вы хотите добавить существующий пользователь к нескольким вторичным группам в одной команде, используйте usermod команды , за которой следует -G названия опции группы , разделенной , (запятые):

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

Чтобы удалить пользователя из группы, используйте команду gpasswd с параметром -d .

В следующем примере мы удаляем username из имени группы groupname :

Как создать группу

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

Как удалить группу

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

Как изменить основную группу пользователя

Чтобы изменить основную группу пользователя, используйте команду usermod за которой следует параметр -g :

В следующем примере мы меняем основную группу пользователя linuxize на developers :

Как создать нового пользователя и назначить группы одной командой

Следующая команда useradd создает нового пользователя с именем nathan с users первичной группы и вторичными группами wheel и разработчиками.

Показать группы пользователей

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

Если вы опустите имя пользователя, команда напечатает информацию о текущем вошедшем в систему пользователе. Проверим пользовательский linuxize :

Из вывода выше мы видим, что основная группа пользователя — это users и она принадлежит к дополнительным группам wheel , storage , libvirt , docker и kvm .

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

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

Выводы

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

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

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

How to Add a User to a Group in Linux

You can add a user to a group in Linux using the usermod command. To add a user to a group, specify the -a -G flags. These should be followed by the name of the group to which you want to add a user and the user’s username.

    Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses

    Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses

Linux groups are collections of users and are used to define a set of privileges those users share. You may be asking yourself: How can I add a user to a group on the Linux operating system?

In this guide, we’re going to discuss how to add a user to a group in Linux. We’ll give you an example of how to add an existing user to a group. In addition, we’ll talk about how to add a new user to a group.

What is a Linux Group?

Linux groups help developers manage user accounts in Linux. You can set individual permissions for each user. But, this can be impractical if you’re working with multiple users who should all have the same privileges.

    Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses

Using groups, you can specify which users can read, write or execute a specific resource on a Linux computer. For instance, we could specify that only a member of the “careerkarma” group could access the “/home/careerkarma/tutorials” folder on a server.

Читайте также:  Ddos сервера kali linux

There are two types of Linux groups:

  • Primary group: This is the same as your login name and is the main group of which your user is a part. Your files cannot be accessed by other members of a group on a Linux computer.
  • Secondary group: Secondary groups, also known as supplementary groups, let you share access to files.

To add a user to a group, you’ll need to use the Linux sudo command. This is because adding users to a group modifies their access permissions to files.

Now that we know the basics of groups on Linux systems, let’s dive into how to add users to a group.

Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!

Venus, Software Engineer at Rockbot

Find Your Bootcamp Match

How to Add a User to a Group Linux

The usermod command adds a user to a Linux group. -a -G flags should be used to add an existing user account to a group. The syntax for the usermod command is: usermod -a -G groupname username.

Let’s break down this syntax:

  • The -a flag tells usermod to add a user to a group.
  • The -G flag specifies the name of the secondary group to which you want to add the user.

If you want to change a user’s primary group, you can use the -g flag instead. You need to use the sudo command to use usermod:

This is because usermod requires sudo privileges. This makes sense because usermod directly modifies user accounts on a Linux system.

Linux: Add User to Group Example

Let’s say you want to add the user “careerkarma” to the “sudo” group on our computer. We could do so using this command:

This command will add “careerkarma” to the “sudo” group. You won’t see any output from this command.

But if you try to access a file that was only accessible to another group, you’ll see that your privileges have changed. In this case, now the “careerkarma” user can use “sudo” to access files because it has been added to the “sudo” group.

If you want to add a user to multiple groups, you can use the same command as above. But, you should separate the group names to which you want to add the user. To add “careerkarma” to both the “sudo” and “test” groups, we could use this command:

We have added the “careerkarma” user to our two groups. Because our user is now part of the sudo group, they can execute the “sudo” command. Our user can also execute any other Linux command that require sudo privileges.

We can also access all the files accessible to the “test” group.

Add User to Group Linux: New User Example

There may be a case where you want to create a new user and immediately add them to a group. That’s where the useradd command comes in. The useradd command allows you to create a new user and by also using the -g option, add the user to a group.

Suppose we want to create a new user called cktutorials and add them to the primary group “staff” and secondary group “test”. We could do so using this command:

We need to add “sudo” to the start of our command so it appears as “sudo useradd …” This is because, like usermod, useradd relates to accounts on the file system. These accounts are protected by sudo.

How to Check a User’s Group

The id command gives you the ability to see all the groups to which a user has access. This makes it easy to see whether you have successfully added a user to a group in Linux.

Here’s the syntax for the id command:

We see an output like this:

This tells us that the primary group of which “careerkarma” is a part is “staff”. We have shortened this output for brevity because this command can return a long list of groups, depending on how your system is configured.

Conclusion

The usermod command allows you to add users to groups in Linux. If the user you want to add to a group does not already exist, you can use the useradd -g command.

Читайте также:  Windows 10 1909 x86 iso

To learn more about usermod and useradd commands, run the man command in your terminal, followed by the command name. This will allow you to see the user manual for that command, which will provide you with more examples and flags you can use.

For advice on top Linux learning resources, courses, and books, read our complete How to Learn Linux guide.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

Как добавить пользователя в группу 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

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

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

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

sudo apt install gnome-system-tools

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

Выводы

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

Источник

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