Groupadd linux для чего

10 groupadd command examples in Linux [Cheat Sheet]

In Linux, groups help to set permission on the group level instead of each individual user. Users can be added to a group and have the same privileges of reading, writing, or executing permission for a particular file. Linux has two types of groups: primary group and secondary group. Each user must belong to one primary group. A user can be assigned to zero or multiple secondary groups.

groupadd command in Linux is used to create a new user group in the system. It uses the values specified on the command line plus the default values from the system.

Syntax for groupadd command

The syntax for the groupadd command is:

Some important options in groupadd are:

  • -g: Use the specified GID for the new group
  • -o: Allow to create groups with duplicate (non-unique) GID
  • -p: Use the given encrypted password for the new group
  • -r: Create a system group
  • -h: Display help message and exit

Different examples to use groupadd command

1. Create a new group

The following command creates a new group student in the system.

Sample Output:

The file /etc/group contains the group account information.

groupadd command to create a new group

2. Create a new group with a specific group ID

When no group ID is specified, groupadd assigns the group ID automatically which is greater than the id of other groups already present. You can create a new group with a specific group ID using -g or —gid option.

$ sudo groupadd staff -g GID
$ sudo groupadd staff --gid GID

Sample Output:

groupadd command to create a new group with a specific group id

3. Overrides /etc/login.defs defaults

The -K or —key option overrides /etc/login.defs defaults (GID_MIN, GID_MAX and others). Multiple -K options can be specified.

The default GID_MIN and GID_MAX values are 1000 and 60000 respectively. You can set your own values using -K or —key option.

The following command creates a new group computer with group ID from 5000 to 7000.

$ sudo groupadd computer -K GID_MIN=5000 -K GID_MAX=7000
$ sudo groupadd computer --key GID_MIN=5000 --key GID_MAX=7000

Sample Output:

groupadd command to change group id min and maxvalues

4. Create a new group with a non-unique GID

Generally, the group ID value must be unique and non-negative. But, the option -o or —non-unique allows you to create groups with duplicate (non-unique) GID.

$ sudo groupadd -o linux -g GID
$ sudo groupadd --non-unique linux --gid GID

Sample Output:

groupadd command to create groups with non-unique gid

5. Create a system group

You can create a new system group using -r or —system group. The group IDs of new system groups are chosen in the SYS_GID_MIN (100) to SYS_GID_MAX (999) range, defined in /etc/login.defs .

$ sudo groupadd --system employee

Sample Output:

Читайте также:  Создать файл через командную строку linux

groupadd command to create a system group

6. Forcefully create a group (even if it already exists)

The -f or —force option forces groupadd command to simply exit status even if the specified group already exists.

$ sudo groupadd --force employee

Sample Output:

groupadd command to exit with success status if the specified group already exists

When -f or —force is used with -g , and the specified GID already exists, another (unique) GID will be assigned (i.e. -g is turned off).

7. Use an encrypted password for the new group

The -p or —password option allows you to specify an encrypted password for the new group. The default is to disable the password.

The following command creates a new group company with a password pa55word .

$ sudo groupadd company -p pa55word
$ sudo groupadd company --password pa55word

Sample Output:

The file /etc/gshadow contains the secure group account information.

groupadd command to create a new group with a password

8. Add an existing user to a group

You can add a user to a group using the usermod command. The following command changes the primary group of a user bikash to student .

$ sudo usermod -g student bikash

Sample Output:

usermod command to change primary group of a user

9. Add an existing user to secondary groups

Each user can have only one primary group, but we can assign them to zero or multiple secondary groups. To add a user to secondary groups, you have to use the -G option.

golinux@ubuntu-PC:~$ sudo usermod -G computer bikash golinux@ubuntu-PC:~$ id bikash uid=1003(bikash) gid=1004(student) groups=1004(student),5000(computer)

10. Create a new user with a specific group

When creating a new user, useradd command provides the same group name as the username and the same group ID as the user ID. You can use -g option to assign a different group name to a new user. The group name must be already present in the system.

The following command creates a new user deepak with group employee .

golinux@ubuntu-PC:~$ sudo useradd -g employee deepak golinux@ubuntu-PC:~$ golinux@ubuntu-PC:~$ id deepak uid=1004(deepak) gid=997(employee) groups=997(employee)

Conclusion

groupadd command is useful for creating new groups in the Linux system. We hope this article helps you to understand how to use groupadd command to add new groups. We also showed how you can add a user to an existing group. If you still have any confusion, let us know in the comment section below.

Источник

DESCRIPTION

The groupadd command creates a new group account using the values specified on the command line plus the default values from the system. The new group will be entered into the system files as needed.

Groupnames may contain only lower and upper case letters, digits, underscores, or dashes. They can end with a dollar sign. Dashes are not allowed at the beginning of the groupname. Fully numeric groupnames and groupnames . or .. are also disallowed.

Groupnames may only be up to 32 characters long.

OPTIONS

The options which apply to the groupadd command are:

This option causes the command to simply exit with success status if the specified group already exists. When used with -g, and the specified GID already exists, another (unique) GID is chosen (i.e. -g is turned off).

-g, —gid GID

The numerical value of the group’s ID. GID must be unique, unless the -o option is used. The value must be non-negative. The default is to use the smallest ID value greater than or equal to GID_MIN and greater than every other group.

Читайте также:  Linux filesystem for ssd

See also the -r option and the GID_MAX description.

-K, —key KEY=VALUE

Overrides /etc/login.defs defaults (GID_MIN, GID_MAX and others). Multiple -K options can be specified.

Example: -K GID_MIN=100 -K GID_MAX=499

Note: -K GID_MIN=10,GID_MAX=499 doesn’t work yet.

permits the creation of a group with an already used numerical ID. As a result, for this GID, the mapping towards group NEWGROUP may not be unique.

-p, —password PASSWORD

defines an initial password for the group account. PASSWORD is expected to be encrypted, as returned by crypt (3).

Without this option, the group account will be locked and with no password defined, i.e. a single exclamation mark in the respective field of ths system account file /etc/group or /etc/gshadow.

Note: This option is not recommended because the password (or encrypted password) will be visible by users listing the processes.

You should make sure the password respects the system’s password policy.

The numeric identifiers of new system groups are chosen in the SYS_GID_MINSYS_GID_MAX range, defined in login.defs, instead of GID_MINGID_MAX.

-R, —root CHROOT_DIR

Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. Only absolute paths are supported.

-P, —prefix PREFIX_DIR

Apply changes to configuration files under the root filesystem found under the directory PREFIX_DIR. This option does not chroot and is intended for preparing a cross-compilation target. Some limitations: NIS and LDAP users/groups are not verified. PAM authentication is using the host files. No SELINUX support.

The default behavior (if the -g, -N, and -U options are not specified) is defined by the USERGROUPS_ENAB variable in /etc/login.defs.

CONFIGURATION

The following configuration variables in /etc/login.defs change the behavior of this tool:

GID_MAX (number), GID_MIN (number)

Range of group IDs used for the creation of regular groups by useradd, groupadd, or newusers.

The default value for GID_MIN (resp. GID_MAX) is 1000 (resp. 60000).

MAX_MEMBERS_PER_GROUP (number)

Maximum members per group entry. When the maximum is reached, a new group entry (line) is started in /etc/group (with the same name, same password, and same GID).

The default value is 0, meaning that there are no limits in the number of members in a group.

This feature (split group) permits to limit the length of lines in the group file. This is useful to make sure that lines for NIS groups are not larger than 1024 characters.

If you need to enforce such limit, you can use 25.

Note: split groups may not be supported by all tools (even in the Shadow toolsuite). You should not use this variable unless you really need it.

SYS_GID_MAX (number), SYS_GID_MIN (number)

Range of group IDs used for the creation of system groups by useradd, groupadd, or newusers.

The default value for SYS_GID_MIN (resp. SYS_GID_MAX) is 101 (resp. GID_MIN-1).

Источник

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

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

Читайте также:  How to install telegram desktop linux

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

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

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

groupadd [OPTIONS] GROUPNAME 

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

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

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

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

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

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

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

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

groupadd: group 'mygroup' already exists 

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

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

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

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

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

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

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

getent group | grep mygroup

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

groupadd: GID '1010' already exists 

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

groupadd -o -g 1010 mygroup

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

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

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

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

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

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

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

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

groupadd -K GID_MIN=1200 -K GID_MAX=1500 mygroup

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

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

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

groupadd -p grouppassword mygroup

Выводы

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

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

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

Источник

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