Как создать группу в linux
Перейти к содержимому

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

  • автор:

Как создать группу 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, достаточно добавить строку:

sudo vi /etc/group

Всё. Теперь нашу группу можно использовать, например, добавим в неё пользователя:

usermod -aG group7 имя_пользователя

Вы уже знаете, как создать группу пользователей linux двумя способами, теперь разберёмся, как её удалить.

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

Если вы создали группу неправильно или считаете, что она не нужна, то её можно удалить. Для этого используйте:

sudo groupdel имя_группы

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

Выводы

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

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

Как создавать группы в Linux (команда groupadd)

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

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

Синтаксис команды groupadd

Общий синтаксис команды groupadd следующий:

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

При вызове groupadd создает новую группу, используя параметры, указанные в командной строке, плюс значения по умолчанию, указанные в файле /etc/login.defs .

Создание группы в Linux

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

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

Команда добавляет запись для новой группы в файлы /etc/group и /etc/gshadow .

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

Если группа с таким именем уже существует, система напечатает сообщение об ошибке, подобное следующему:

Чтобы подавить сообщение об ошибке, если группа существует, и для успешного завершения команды используйте параметр -f ( —force ):

Создание группы с определенным GID

В Linux и Unix-подобных операционных системах группы идентифицируются по имени и уникальному GID (положительное целое число).

По умолчанию, когда создается новая группа, система назначает следующий доступный GID из диапазона идентификаторов групп, указанных в файле login.defs .

Используйте параметр -g ( —gid ), чтобы создать группу с определенным GID.

Например, чтобы создать группу с именем mygroup с GID 1010 , введите:

Вы можете проверить GID группы, перечислив все группы и отфильтровав результат с помощью grep :

Если группа с данным GID уже существует, вы получите следующую ошибку:

При использовании с параметром -o ( —non-unique ) команда groupadd позволяет создать группу с неуникальным GID:

Создание системной группы

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

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

Используйте параметр -r ( —system ), чтобы создать системную группу. Например, чтобы создать новую системную группу с именем mysystemgroup вы должны запустить:

Переопределение значений /etc/login.defs по умолчанию

Параметр -K ( —key ), за которым следует KEY=VAL позволяет переопределить значения по умолчанию, указанные в файле /etc/login.defs .

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

Допустим, вы хотите создать новую группу с GID в диапазоне от 1200 до 1500. Для этого укажите минимальные / максимальные значения, как показано ниже:

Создание системной группы с паролем

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

Параметр -p ( —password ), за которым следует пароль, позволяет вам установить пароль для новой группы:

Выводы

В Linux вы можете создавать новые группы с помощью команды groupadd .

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

Users, Groups and Permissions in Linux

Żimuzo Obiechina

So here I am, in my journey to mastery, documenting how I learnt to create users, groups and permissions in Linux in the form of a mini-tutorial.

We’ll be working with Ubuntu installed on a local virtual server — but most commands used will apply to any other Linux distribution. This article also assumes a basic knowledge of Linux commands.

The Linux operating system allows multi-user functionality. This means that multiple users can use the operating system concurrently and independently while sharing system resources.

In this mini-tutorial, we will create 3 groups and 15 users and assign these users across the 3 groups. We will also ensure that users in one group cannot access files in another group unless they are added to that group.

But first, let’s take a look at the different types of user accounts in Linux.

Types of user accounts

There are three basic types of Linux user accounts:

  1. Root user(administrative): This user account has full access to system-wide resources, in addition to the permission to create, modify and delete users and groups.
  2. Regular user accounts: These are user accounts with a login shell and home directory that perform tasks for personal use — usually common application tasks that are isolated to the user’s home directory.
  3. Service accounts: These are accounts assigned to applications but with limited access in order to protect the application from potential attacks while still performing essential functions. They usually will not have a home directory.

Create users

We will need admin privileges to create users — however, using the root user context is generally avoided, for security reasons.

First, create a regular user using the useradd command following this syntax:

TIP: To learn more about a Linux command, run man <command> , for example, man useradd to display a full description of the command.

And then, assign admin privileges to this user as follows:

Now, this admin user has superuser privileges and will not need to type in a password with the sudo command.

Let’s switch to the admin superuser using the following command:

And then create more users with the useradd command:

Do this for the number of users you need to create — 15 users in this case.

View users

All users in the system are stored in the /etc/passwd directory. To view all users, run the following command:

This should output something similar to the following:

Each entry has the following features:

  • the username: user1
  • the encrypted password: x
  • the unique identifier (UID) for the user: 100x
  • the user group ID (GID): 100x
  • the General Electric Comprehensive Operating Supervisor (GECOS) field — which is empty in this case. (This field contains general information as a string of comma-delimited attributes, for example, full name; phone number; etc)
  • the user home directory: /home/user1
  • the default login shell for the user: /bin/sh

Delete users

To delete a user, run the command:

This removes all related user data, along with all the files in the user’s home directory -f, —force .

Add users to a group

To add the 15 users to groups, let’s create three different groups — a group for team leads leads , one for developers developers and another for the site reliability engineering team sre — and then add the users to the groups.

Use the groupadd command to create a group with the following syntax:

So for our case, we will create three different groups like so:

Next, add the already created users to each group assuming each user fits the group role, using the gpasswd command with the following syntax:

The gpasswd command allows you to manage the creation of groups and members of groups — the -A flag defines group administrators and the -M flag defines the members of the group as a comma-separated list (see the man pages for more details).

View groups

All groups in the system are stored in the /etc/groups directory. To view all groups, run the following command:

This should give an output similar to:

Next, let’s define the level of access allowed for each group.

Permissions and Ownership

The reason Linux so elegantly supports a multi-user system is as a result of permissions. Permissions grant users the right to access files and directories within the system. In Linux, the basic permissions are:

  • Read : the right to open and view the contents of files and directories. Represented by r
  • Write: the right to modify the content of a file and to add, remove and rename files within a directory. Represented by w
  • Execute: the right to run a script or application. Represented by x

Let’s demonstrate the significance of file permissions; create 3 separate files using the following command:

Run the following command to view the files and the current permissions on each file:

The output of this command should be similar to this:

The parts of the above output relevant to the level of access are the following:

  • The first ten characters -rw-r—r— symbolize the file access permissions:
  • the first character refers to the file type, where — means a regular file. Other notations are d for a directory, l for a symbolic link, and so on.
  • the other nine characters define access permissions to the file type — the first three characters rw- are user permissions, the next three r— are group permissions while the last three r— are permissions for all other users.
  • root: the user that owns (created) the file
  • root : the group that owns the file

With the above information in mind, we will assign a specific group to its related file.

Assign Group Ownership

We want each file to belong to its own group. To do this, let’s assign group ownership using the chgrp (short for change group) command. The syntax for this command is:

So, for our example, we’ll run the following commands:

Now, when we run the ls -l command, we should get the following output:

Each file now belongs to its respective group. This means that only members of the group that owns the file can have whatever permissions specified; that is, read permission (as demonstrated by the middle three characters r— ). However, all other users outside of the group also have read permissions (as demonstrated by the last three characters r— ).

So, considering we want to restrict file access to only members belonging to the file group, let’s change that.

Modifying permissions

To set or change permissions, use the chmod (short for change mode) command (see the man pages for more details).

When using this command, we specify the following:

  • Whom to change permissions for: u for the user(owner), g for thegroup and o for all other users.
  • How to change permission: + (plus sign) to add permissions, — (minus sign) to remove permissions or = (equal sign) to leave as is.
  • What permission to change: r for read, w for write, x for execute.

Using the information above, let’s take away the read permission for users outside the group and add write and execute permissions to the group as follows:

Run the ls -l command to view the modified permissions. The output should be:

To demonstrate that files belonging to one group cannot be accessed by another group, login as a different user; for example, user5 (who belongs to the developers group), using the following command:

Now, let’s attempt to read a file that does not belong to the developers group. Run the following command to view the leads.txt file:

You should get a warning that says:

This is expected because user5 does not have the permission to read the contents of the leads.txt file since the file belongs to the leads group, and not the developers group.

Conclusion

The information shared in this mini-tutorial is by no means exhaustive of the topic of managing users, groups and permissions in Linux. But this should get any beginner, such as myself, up and running with working in Linux.

PS: I decided to have some fun while learning bash scripting, and wrote scripts create_users.sh and delete_users.sh to automate creating and deleting the users described above. See them here.

— — — — — — — — — Thank you for reading! — — — — — — — — —

How To Create and Manage Groups in Linux

How To Create and Mange Groups in Linux

A group is a collection of users in Linux that shares some commonalities for the purpose of security, privilege, etc.

If you are not familiar with Linux permissions and how to manage them, take a look at this article.

In this tutorial, we will cover how to create groups in Linux and briefly explain how to manage them.

Table of Contents

Types of groups in Linux

There are mainly two types of groups in Linux:

  1. Primary Group: Each user belongs to a primary group. The group is created when the user is created, and the name of the user and the group is generally the same.
  2. Secondary Group: A user may belong to one or more secondary groups except from the primary group. Secondary groups are useful for managing permissions for multiple users.

While every user has a primary group they belong to, the users may not belong to any secondary group at all. This will become clearer when we show you how to create new users and add them to a new or existing group.

Basic management of groups and users

The groupadd command is the most used tool for creating new groups. The basic syntax of the groupadd command is:

You can view all the available options in the help menu of the command. Type in groupadd -h in the terminal to read the description of all the options.

Viewing existing groups on Linux

Chances are there will be many different groups in your Linux system by default. This is because a lot of software and system packages also create their own users and groups to function properly.

There is a file (/etc/group) that lists all the groups present in a Linux system. This file has the name of all the groups and the users that belong in those groups.

To view all the groups, we can just cat the file:

The leftmost names in the list before the first colon are the name of the groups. The next x after the first colon indicates the password field, which is not stored in this file. The number after the second colon represents the group id (gid). The last field after the third colon is where the users are listed belonging to the group. For example, the user syslog and edxd belong to the group adm marked in green.

You can also view the groups using the getent (get entries) command:

The command getent is used for viewing the entries in some text databases. Some examples of these databases would be the group file, passwd file, etc.

Create a new group with the groupadd command

To create a new group using the groupadd command, you just have to specify the group name after the command. Remember to use sudo before the command to get root privileges:

Now let’s take a look at the /etc/group file to see if this new group was added to the list:

As you can see, the group bytexd_group has been created with the group id (gid) of 1007. This is how you can create new user groups. Now let’s learn how to add a user to an existing group.

Create a group with a custom group id (gid)

In Linux, when a new group is created, the group is assigned a unique identifier number, called the group id or GID in short.

The GIDs are assigned using the next available number in the system file named login.defs.

We can use the -g or —gid flag to specify the gid when creating a group. Let’s create a group with a gid of 1100:

Let’s see if the group was created or not. Type in:

As you can see, the group new_gid has been created with the group id (gid) of 1100. If the gid you specified is already used to identify a group, you can use the -o flag to specify a non-unique option, which will allow you to create multiple groups with the same group id.

Creating a new user using the useradd command

We can use the useradd command to create a new user on Linux:

To view the new created user, you can follow the same method used for the group. The users are listed on a file called passwd (/etc/passwd) on Linux:

Or, use the getent command:

As you can see in the output, the new user bytexd_user has been created. In the passwd file, the first string before the colon is the username, the second string is the password (in this case x, or hidden). The numbers in the third and fourth field are the user id (uid) and the group id (gid) respectively. The next field is for the full name of the user, and the next one is the home directory for the user. The last field is the location of the shell for the user.

Do you remember the types of groups that we talked about at the beginning of the article? Let’s check out if adding this new member created a primary group for the user bytexd_user. We’ll use grep to filter out the result that we are looking for:

From the output, we can see that Linux created a new group named bytexd_user with the group id (gid) of 1101.

If you take a look at the previous command’s output, you’ll see that the gid of the user is 1002 ( bytexd_user:x:1002:1101::/home/bytexd_user:/bin/sh ). This proves that the user bytexd_user does belong to the primary group with the same name and gid = 1002.

Adding an existing user to existing groups

Now that we have created a new group (bytexd_group) and a new user (bytexd_user), let’s see how we can add the new user to our new group. The usermod command is used to modify a user account. We will be using this command with the -a flag to add a user to an existing group.

Let’s look at the syntax of the command:

Now let’s add bytexd_user to bytexd_group:

Let’s take a look at the change:

As you can see, the bytexd_user has been added to the group bytexd_group. You can also add a user to multiple existing groups at once separating the group names by comma:

Now let’s see where we can utilize this functionality of adding a user to an existing group.

Adding a user to the sudo group

As you know, the sudo group in Linux has the administrator/root privileges.

If you want to give access to root privileges to a user, you can simply add the user to the sudo group. I’ll type in the following to give bytexd_user sudo privileges:

Now let’s see who belongs to the sudo group:

Isn’t this great? Now our newly created user bytexd_user can utilize the sudo privileges. This is how useful the groups in Linux are. Try out on your own and see if you can grant sudo privileges to a user who did not have it before.

Display user and group information

To get the detail information for a user, we can use the id command followed by the username:

The output shows the user id, group id, and the group names that the user belongs to.

Changing primary group for an existing user

We can use the usermod command with the lowercase -g flag to change the primary group an existing user belongs to. The command syntax is as follows:

Now that we’ve learned how to add users and groups in all sorts of ways, let’s learn how to remove them.

Remove a user from a group

To remove a user from a specific group, we can use the gpasswd command with a -d flag. Here is the syntax:

Let’s remove bytexd_user from sudo group:

Removing user bytexd_user from group sudo:

Check if the sudo group has bytexd_user user:

As you can see, there is no bytexd_user listed in the output.

How to delete a user

We will use the userdel command to remove a group. The syntax is as follows:

Let’s delete the user we created (bytexd_user):

Let’s check if we have any user named bytexd_user:

The output shows no entries. Thus, the user called bytexd_user has been deleted.

How to delete a group

The command groupdel can be used to remove a group. The syntax is as follows:

Now let’s delete the group we created earlier (bytexd_group):

Let’s check if there is any group called bytexd_group:

The output shows no entries listed. Thus, the group named bytexd_group has been deleted.

Conclusion

In this tutorial, we covered the basics you will require to manage groups and users on Linux. This was a brief tutorial introducing the topic at hand. If you want to learn more, you can use the manual of the commands we have used in this tutorial (groupadd, useradd, usermod, userdel, groupdel, etc.).

Type in man [command_name] in the terminal to access the dedicated manuals for each of the commands.

We hope you liked the tutorial. If you have some questions or comments in general, feel free to leave them down below and we’ll get back to you as soon as possible. Thank you for reading!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *