How to Create Groups in Linux (groupadd Command)
In Linux, groups are used to organize and administer user accounts. The primary purpose of groups is to define a set of privileges such as reading, writing, or executing permission for a given resource that can be shared among the users within the group.
In this article, we will talk about how to create new groups in Linux, using the groupadd command.
groupadd Command Syntax #
The general syntax for the groupadd command is as follows:
Only the root or a user with sudo privileges can create new groups.
When invoked, groupadd creates a new group using the options specified on the command line plus the default values specified in the /etc/login.defs file.
Creating a Group in Linux #
To create a new group type groupadd followed by the new group name.
For example, to create a new group named mygroup you would run:
The command adds an entry for the new group to the /etc/group and /etc/gshadow files.
Once the group is created, you can start adding users to the group .
If the group with the same name already exist, the system will print an error message like the following:
To suppress the error message if the group exist and to make the command exit successfully, use the -f ( —force ) option:
Creating a Group with Specific GID #
In Linux and Unix-like operating systems, groups are identified by its name and a unique GID (a positive integer).
By default, when a new group is created, the system assigns the next available GID from the range of group IDs specified in the login.defs file.
Use the -g ( —gid ) option to create a group with a specific GID.
For example to create a group named mygroup with GID of 1010 you would type:
You can verify the group’s GID, by listing all groups and filtering the result with grep :
If a group with the given GID already exist, you will get the following error:
When used with the -o ( —non-unique ) option the groupadd command allows you to create a group with non-unique GID:
Creating a System Group #
There is no real technical difference between the system and regular (normal) groups. Usually, system groups are used for some special system operation purposes, like creating backups or doing system maintenance.
System groups GIDs are chosen from the range of system group UDs specified in the login.defs file, which is different than the range used for regular groups.
Use the -r ( —system ) option to create a system group. For example, to create a new system group named mysystemgroup you would run:
Overriding the Default /etc/login.defs Values #
The -K ( —key ) option followed by KEY=VAL allows you to override the default values specified in the /etc/login.defs file.
Basically, all you can override are the maximum and minimum values of the normal and system group IDs for automatic GID selection when creating a new group.
Let’s say you want to create a new group with GID in the range between 1200 and 1500. To do that, specify the min/max values as shown below:
Creating a System Group with Password #
Adding a password to a group has no practical use and may cause a security problem since more than one user will need to know the password.
The -p ( —password ) option followed by password allows you to set a password for the new group:
Conclusion #
In Linux, you can create new groups using the groupadd command.
The same instructions apply for any Linux distribution, including Ubuntu, CentOS, RHEL, Debian, Fedora, and Arch Linux.
Feel free to leave a comment if you have any questions.
Как создать группу Linux
Группы — очень удобный инструмент распределения прав в Linux. Благодаря группам можно разрешить нескольким пользователям доступ к одному файлу или папке, а другим запретить, не прибегая к более сложным технологиям, таким, как ACL-списки. Системные сервисы тоже запускаются от имени определённых пользователей, и поэтому группы позволяют очень тонко настроить права доступа к нужным файлам для сервисов, не давая им полного доступа к системе.
В этой небольшой статье мы рассмотрим, как создать группу Linux разными способами, а также поговорим о дополнительных настройках группы.
Как создать группу Linux
Для создания групп в Linux используется команда groupadd, давайте рассмотрим её синтаксис и опции:
$ groupadd опции имя_группы
А теперь разберём опции утилиты:
- -f — если группа уже существует, то утилита возвращает положительный результат операции;
- -g — установить значение идентификатора группы GID вручную;
- -K — изменить параметры по умолчанию автоматической генерации GID;
- -o — разрешить добавление группы с неуникальным GID;
- -p — задаёт пароль для группы;
- -r — указывает, что группа системная;
- -R — позволяет изменить корневой каталог.
Перейдём к практике. Всё очень просто. Создадим группу group1:
sudo groupadd group1
Теперь вы можете убедится, что группа была добавлена в файл /etc/group:
cat /etc/group | grep group1
Система создала группу с GID 1001. Вы можете вручную указать GID вашей группы с помощью опции -g;
sudo groupadd -g 1006 group6
Также есть возможность задать пароль для группы. Он служит для того, чтобы пользователи, не состоящие в группе, смогли получить к ней доступ с помощью команды newgrp. Эта команда делает пользователя участником указанной группы до конца сеанса. Из соображений безопасности этот метод использовать не рекомендуется, поскольку один пароль будут знать несколько пользователей. Чтобы создать группу с паролем, сначала создаём пароль командой:
perl -e ‘print crypt(«12345», «xyz»),»\n»‘
Здесь xyz — это случайная комбинация символов для увеличения надёжности пароля, а 12345 — ваш пароль. Мы должны передать утилите именно зашифрованный пароль, если передать его в открытом виде, то ничего работать не будет. Теперь создаём группу с только что полученным паролем:
sudo groupadd -p sajEeYaHYyeSU group7
Затем можно попытаться получить временный доступ к ресурсам группы с помощью newgrp:
newgrp group7
groups
Нам надо ввести пароль, который мы раньше шифровали, и теперь до конца сеанса наш пользователь находится в группе. Если вы хотите добавить пользователя в группу навсегда, то надо использовать команду usermod:
sudo usermod -aG group7 имя_пользователя
Создание группы Linux вручную
Если вы не хотите создавать группу с помощью команды, это можно сделать, просто редактируя конфигурационные файлы. Все группы, которые существуют в системе, находятся в файле /etc/group. Если мы хотим добавить новую, достаточно добавить строчку с таким синтаксисом:
имя_группы : х : gid : список_пользователей
Разберём более подробно, какой параметр за что отвечает:
- имя_группы — имя, которое будет использоваться для операций с группой;
- x — заглушка пароля группы, пароль указывается в файле /etc/gshadow, если в этом есть необходимость;
- gid — идентификатор группы;
- список_пользователей — пользователи, разделённые запятыми, которые входят в группу.
Таким образом, чтобы создать группу group7, достаточно добавить строку:
Всё. Теперь нашу группу можно использовать, например, добавим в неё пользователя:
usermod -aG group7 имя_пользователя
Вы уже знаете, как создать группу пользователей linux двумя способами, теперь разберёмся, как её удалить.
Как удалить группу в Linux
Если вы создали группу неправильно или считаете, что она не нужна, то её можно удалить. Для этого используйте:
sudo groupdel имя_группы
Только ни в коем случае не удаляйте системные группы, они нужны и используются системой, а их удаление может сломать работу некоторых программ.
Выводы
В этой небольшой статье мы рассмотрели создание группы в Linux, а также то, как удалить созданную группу. Как видите, это довольно просто. Ели у вас остались вопросы, спрашивайте в комментариях!
Create New Groups in Linux With Groupadd Command
The groupadd command in Linux creates new groups. Learn how to use groupadd command to add new groups in Linux.
Table of Contents
While the useradd command creates new users, the groupadd command in Linux creates new groups. It updates the /etc/group file accordingly.
There are not many options with groupadd and its syntax is pretty basic:
Let’s see how to use groupadd command for creating groups in Linux.
Groupadd command examples
Please keep in mind that adding group is administrative task and hence you need to be root or have sudo rights. Read more about creating sudo user here.
1. Create a new group
To create a new group in Linux, you can use it in the following manner:
You can verify that the new group has been created by checking the /etc/group file:
What do you do with a group? You should have some users in it, right? You can add users to group using the usermod command. If you want to add multiple users to a group at the same time, you can use the gpasswd command like this:
2. Create a group with specific group ID (gid)
By default, the new group gets created with a group id higher than the GID_MIN value defined in /etc/login.defs. On most Linux system, this value is 1000.
In other words, you get one of the first available GID after 1000.
But you are not restricted to that. You can create a group with a specific GID in this manner:
3. Create a new system group
When you create a new group, it’s a normal group with GID higher than 1000. You can also create a system group that automatically takes a group id between SYS_GID_MIN and SYS_GID_MAX as defined in /etc/login.defs.
You can see in the example that the group id is less than 1000 and thus indicating that it is not a normal group but a system group (used for system programs).
I hope you find this quick little tutorial helpful in using groupadd command. You may also checkout how to delete groups with groupdel command.
Any questions or suggestions are always welcomed.