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

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

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.

Читайте также:  Windows под номером 10

Для установки инструмента в CentOS выполните:

sudo yum install system-config-users

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

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

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

sudo apt install gnome-system-tools

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

Выводы

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

Источник

How to Add User to a Group in Linux

Home » SysAdmin » How to Add User to a Group in Linux

In Linux, a group is a unit in which you can manage privileges for several users simultaneously. Linux groups allow you to manage multiple user permissions quickly and easily.

In this tutorial learn how user groups work in Linux, and how to add users to specific groups.

  • A system running Linux
  • A user account with sudo or root privileges
  • Access to a terminal window/command line (Ctrl-Alt-T, Ctrl-Alt-F2)

What is a User Group in Linux

In Linux, different users have different roles or responsibilities. Some users might need the ability to execute applications, while others are restricted from accessing specific files and folders.

Groups let you create categories of users with pre-set permissions. Instead of managing permissions for each user account, you can simply add a user to a group to grant the appropriate permissions.

Primary Group

The primary group is set to the logged-in user. Any files the user creates are automatically added to that group. A user can only belong to one primary group at a time. A primary group with the same name as the user is created, and any files created by the user are included in that group.

Secondary Groups

A user can belong to any number of secondary groups (including none). Secondary groups are created to manage individual files and software applications. Members of the group inherit the read, write, and execute privileges for that group.

How to Create a User Group

To create a new group, enter the following:

Replace new_group with the name you want for your new group.

How to Add User to Group

Add an Existing User to an Existing Group

Use the adduser command to add a user to a group:

Use the useradd command to add a user:

You can also use the usermod command to add a user to a group:

The usermod command uses the –append and –group options to append the user to a particular group. Without using –append , the user could be dropped from other groups.

Add a User to Multiple Groups at Once

Use the usermod command to specify multiple groups to add to:

Create a User and Add to Group

This is useful for creating a new user on the fly for a specific software application. Enter the following:

Next, assign a password to the new user:

Change a Users Primary Group

All previous commands have been used to manage the secondary groups a user belongs to. In most cases, a user’s primary group is the same as their username.

To change a users primary group, enter the command:

The lower-case –g specifies the primary group. (Upper-case –G refers to a secondary group.) A user can only have one primary group, so the old primary group user_name won’t be primary anymore for this user.

Читайте также:  Linux mount smb password

How to Remove a User From a Group

The gpasswd tool is used for managing groups. To remove a user from a group:

Note: The gpasswd tool can also be used for other administrative tasks such as defining group administrators and setting a password for access to group resources. Use the Linux man command man gpasswd for details.

Delete a Group

To delete a group, use the command:

How to List Groups in Linux

Linux comes with several different groups by default. Some of these, like the sudo group, can be used to grant permissions. Others are hidden, used for system tasks.

To view a list of groups on your system by displaying the /etc/groups file:

To display the groups that a user belongs to with the groups command:

The image above shows the groups that the logged-in user ‘sofija’ belongs to. You can display groups for a different user by specifying the username:

Another method to display the groups a user belongs to, including user ID (uid) and group ID (gid), is to use the id command:

Other Common Groups

There are a several common group names you might encounter in Linux:

  • sudo – A member of this group can use the sudo command to elevate their privileges
  • wheel – This is an older method of granting sudo-like privileges
  • cdrom – Allows the user to mount the optical drive
  • adm – Allows the user to monitor Linux system logs
  • lpadmin – Allows the user to configure printers
  • plugdev – Allows the user to access external storage devices

You should now have a good understanding of Linux groups and how to add and remove members from those groups. For more information on specific commands, you can enter the man command to display a manual in your terminal window.

Источник

Linux Add User To Group Using Command-Line

  1. 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.
  2. 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:

  1. /etc/passwd – Contains one line for each user account.
  2. /etc/shadow – Contains the password information in encrypted formatfor the system’s accounts and optional account aging information.
  3. /etc/group – Defines the groups on the system.
  4. /etc/default/useradd – This file contains a value for the default group, if none is specified by the useradd command.
  5. /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:

  1. Add a new user called jerry to secondary group named cartoons on Linux:
    sudo useradd -G cartoons jerry
  2. Want to add a new user called tom to primary group called cartoons? Run:
    useradd -g cartoons tom
  3. 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

Источник

Читайте также:  Windows based script host не удается найти файл сценария как убрать
Оцените статью