- Добавление пользователя в группу. Списки пользователей и групп в Linux
- Список групп, в которых состоит пользователь
- Добавление пользователя в группу
- Удаление пользователя из группы
- Список всех групп
- Список всех пользователей
- Как добавить пользователя в группу Linux
- Как добавить пользователя в группу Linux
- Добавление пользователя в группу через GUI
- Выводы
- Linux: Add User to Group
- Add a new Linux User to a Group
- Add Linux Group
- Add User to Group
- Add User to two groups
- Set User password
- Set new primary group
- Add an existing Linux User to a Group
- Usermod command example
- Linux Add User To Group Using Command-Line
- How to add user to group in Linux
- Linux command to add user to group
- How to become a root user
- Add a new user to secondary group using useradd
- How to add a new user to primary group using useradd
- How to add a existing user to existing group using usermod
- usermod command options summary
- A note about security
- A note about GUI tool
- Summing up
Добавление пользователя в группу. Списки пользователей и групп в Linux
В данной заметке рассматривается как добавить пользователя в группу и как удалить из группы, вывод списка групп, в которых состоит пользователь, а также вывод всех пользователей и всех групп в системе Linux.
Список групп, в которых состоит пользователь
Для вывода списка групп, в которых состоит конкретный пользователь используется команда groups.
При выполнении команды groups без аргументов, выводится список групп текущего пользователя.
Можно указать имя пользователя, для которого нужно вывести список групп, в которых он состоит. Например, выведем группы, в которых состоит пользователь root.
Добавление пользователя в группу
Чтобы в Linux добавить существующего пользователя в группу используется команда usermod с ключами -a и -G группа . Например, добавим пользователя pingvinus в группу editorsgroup.
После выполнения данной команды пользователю pingvinus необходимо выйти и снова войти в систему. Можно воспользоваться командой su, чтобы войти от имени пользователя pingvinus в текущем сеансе.
Удаление пользователя из группы
Удалим пользователя pingvinus из группы editorsgroup.
Чтобы изменения вступили в силу, нужно выйти и войти в систему.
Список всех групп
Выведем список всех групп в текущей системе Linux.
Список всех пользователей
Выведем список всех пользователей в текущей системе Linux.
Обычно список довольно большой, так как содержит всех пользователей, включая пользователей, которые используются для запуска некоторых программ и служб.
Можно ограничить вывод только теми пользователями, для которых домашняя директория расположена в директории /home.
Источник
Как добавить пользователя в группу 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. Это может быть очень полезно для предоставления пользователю дополнительных полномочий и разграничения привилегий между пользователями. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
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 Add User To Group Using Command-Line
- Primary user group. – It is the group that applied to you when login. Typically it is same as your login name. All of your process and files (including directories/folders) would have your primary group as the group membership. The primary group allows private group membership and security features. Your files or process cannot access by other group members or users on the Linux system.
- Secondary or supplementary user group – Users can be a member of other groups on the Linux system. It is useful for file sharing and other purposes. A sysadmin can fine-tune security too. For example, if you are a member of a secondary group called cdrom, you can mount and unmout cd-rom drive.
Tutorial details | |
---|---|
Difficulty level | Intermediate |
Root privileges | Yes |
Requirements | usermod/useradd |
Est. reading time | 5 minutes |
How to add user to group in Linux
Please note that all user accounts related information are stored in the following files:
- /etc/passwd – Contains one line for each user account.
- /etc/shadow – Contains the password information in encrypted formatfor the system’s accounts and optional account aging information.
- /etc/group – Defines the groups on the system.
- /etc/default/useradd – This file contains a value for the default group, if none is specified by the useradd command.
- /etc/login.defs – This file defines the site-specific configuration for the shadow password suite stored in /etc/shadow file.
We do not modify these files by hand. Instead, we add a user to a group in Linux using various commands.
Linux command to add user to group
Open the terminal and then type:
- Add a new user called jerry to secondary group named cartoons on Linux:
sudo useradd -G cartoons jerry - Want to add a new user called tom to primary group called cartoons? Run:
useradd -g cartoons tom - We can add a existing user named spike to existing group named cartoons in Linux:
useradd -g cartoons spike
How to become a root user
You must run all command as root user. To become a root user run:
su —
Alternatively use sudo command:
sudo -i
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Add a new user to secondary group using useradd
You need to the useradd command to add new users to existing group (or create a new group and then add user). If group does not exist, create it. The syntax is as follows:
useradd -G < group-name >username
In this example, create a new user called vivek and add it to group called developers. First, make sure group developers exists using grep command:
# grep «^developers» /etc/group
Sample outputs:
If you do not see any output then you need to add group developers using the groupadd command:
# sudo groupadd developers
Verify that user vivek does not exists:
# grep «^vivek» /etc/passwd
You should not see any outputs from above command. Finally, add a new user called vivek to group developers:
# useradd -G developers vivek
Setup password for user vivek:
# passwd vivek
Ensure that user added properly to group developers:
# id vivek
Sample outputs:
Please note that capital G ( -G ) option add user to a list of supplementary groups. Each group is separated from the next by a comma, with no intervening whitespace. For example, add user jerry to groups admins, ftp, www, and developers, enter:
# useradd -G admins,ftp,www,developers jerry
How to add a new user to primary group using useradd
How to add a existing user to existing group using usermod
Add existing user tony to ftp supplementary/secondary group with the usermod command using the -a option
i.e. add the user to the supplemental group(s). Use only with -G option:
# usermod -a -G ftp tony
In this example, change tony user’s primary group to www, enter:
# usermod -g www tony
usermod command options summary
Option | Purpose |
---|---|
-a —append | Add the user to the supplementary group(s). Use only with the -G option. |
-g GROUP —gid GROUP | Use this GROUP as the default group. |
-G GRP1,GRP2 —groups GRP1,GRP2 | Add the user to GRP1,GRP2 secondary group. |
A note about security
If you add or delete user to existing group, you must change the owner of any crontab files or at jobs manually. You must make any changes involving NIS on the NIS server too.
A note about GUI tool
You will probably find the use of the GUI tool easy. KDE user can use KUser tool and the GNOME user can use users-admin:
users-admin is part of the GNOME system tools, a set of tools to easily access and manage system configuration
One can easily add users as follows from the gnome 3 settings on a Debian/Ubuntu Linux:
Fedora/RHEL/CentOS user can use system-config-users command as follows
# system-config-users
$ ssh -X -t vivek@server1.cyberciti.biz sudo system-config-users
Sample outputs:
Click on the Groups tab to add or view groups:
Summing up
You learned how to add a new or existing user to group on Linux operating systems. For more information type the following command at the shell prompt to read man pages:
$ man usermod
$ man useradd
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник