Creating user in linux command

Как создать пользователя Linux

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

Многопользовательская архитектура, одна из первых особенностей Linux, которая существует еще с зарождения системы. В системе могут работать одновременно множество пользователей благодаря удаленному входу, а также пользователи используются для запуска определенных сервисов. В этой статье мы рассмотрим как создать пользователя linux, рассмотрим способ через терминал и в графическом интерфейсе.

Создание пользователя в Linux

Вся информация о пользователях находится в файле /etc/passwd. Мы могли бы создать пользователя linux просто добавив его туда, но так делать не следует, поскольку для этой задачи существуют специальные утилиты. Одна из таких утилит, это useradd. Рассмотрим ее подробнее.

Команда useradd

Это довольно простая команда, которая есть во всех дистрибутивах Linux. Она позволяет зарегистрировать нового пользователя или изменить информацию об уже имеющемся. Во время создания можно даже создать домашний каталог пользователя и скопировать в него системные файлы. Рассмотрим синтаксис команды:

$ useradd опции имя_пользователя

Все довольно просто, дальше нам нужно рассмотреть основные опции команды, с помощью которых вы будете настраивать нового пользователя:

  • -b — базовый каталог для размещения домашнего каталога пользователя, по умолчанию /home;
  • -c — комментарий к учетной записи;
  • -d — домашний каталог, в котором будут размещаться файлы пользователя;
  • -e — дата, когда учетная запись пользователя будет заблокирована, в формате ГГГГ-ММ-ДД;
  • -f — заблокировать учетную запись сразу после создания;
  • -g — основная группа пользователя;
  • -G — список дополнительных групп;
  • -k — каталог с шаблонами конфигурационных файлов;
  • -l — не сохранять информацию о входах пользователя в lastlog и faillog;
  • -m — создавать домашний каталог пользователя, если он не существует;
  • -M — не создавать домашнюю папку;
  • -N — не создавать группу с именем пользователя;
  • -o — разрешить создание пользователя linux с неуникальным идентификатором UID;
  • -p — задать пароль пользователя;
  • -r — создать системного пользователя, не имеет оболочки входа, без домашней директории и с идентификатором до SYS_UID_MAX;
  • -s — командная оболочка для пользователя;
  • -u — идентификатор для пользователя;
  • -D — отобразить параметры, которые используются по умолчанию для создания пользователя. Если вместе с этой опцией задать еще какой-либо параметр, то его значение по умолчанию будет переопределено.
Читайте также:  Oracle client linux install rpm

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

Как видите, по умолчанию домашний каталог пользователя будет создан в /home и будет использоваться оболочка /bin/sh. Теперь создадим минимального пользователя с минимальными настройками:

Был создан самый простой пользователь, без оболочки и пароля, а также без групп. Теперь немного усложним задачу и создадим пользователя с паролем и оболочкой /bin/bash:

sudo useradd -p password -s /bin/bash test1

Для того чтобы получать доступ к системным ресурсам пользователю нужно быть участником групп, у которых есть доступ к этим ресурсам. Дополнительные группы пользователя задаются с помощью параметра -G. Например, разрешим пользователю читать логи, использовать cdrom и пользоваться sudo:

sudo useradd -G adm,cdrom,wheel -p password -s /bin/bash test2

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

sudo useradd -G adm,cdrom,wheel -p password -s /bin/bash -e 01:01:2018 test2

Некоторых пользователей интересует создание пользователя с правами root linux, это очень просто делается с помощью useradd, если комбинировать правильные опции. Нам всего лишь нужно разрешить создавать пользователя с неуникальным uid, установить идентификатор в 0 и идентификатор основной группы тоже в 0. Команда будет выглядеть вот так:

sudo useradd -o -u 0 -g 0 -s /bin/bash newroot

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

Создание нового пользователя linux в GUI

В графическом интерфейсе системы создать нового пользователя linux еще проще. Рассмотрим окружение Gnome, хотя и в KDE тоже есть аналогичная функция. Войдите в главное меню и откройте параметры системы:

Затем откройте «Пользователи»:

Поскольку утилита запущена от имени обычного пользователя вы ничего не можете сделать. Поэтому нажмите кнопку «Разблокировать»:

Только после этого используйте кнопку со знаком плюс для создания нового пользователя Linux:

В открывшемся окне нужно заполнить все поля. Но тут намного больше ограничений, чем в методе через терминал. Вы не можете задать слишком простой пароль, а также нельзя настроить группы. Можно только указать будет ли пользователь включен в группу wheel с помощью выбора типа пользователя — администратор или обычный:

После этого создание пользователя linux завершено, новый пользователь появится в списке.

Выводы

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

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

Источник

How to Create User in Linux [Linux Create User Command]

How to Create User in Linux [Linux Create User Command], Adding users without a graphical user interface (i.e., GUI) can sometimes be cumbersome. Today we will show you how to create new users in Linux and modify the type of user created.

How to Create User in Linux [Linux Create User Command]

List of content you will read in this article:

Читайте также:  Oracle database linux command line

As you know, Linux is a system where multiple people can interact with one system simultaneously. To reach this objective, you can use useradd command in Linux. This command’s primary aim is to Create User in Linux.

If you are a system administrator, you have the authority to manage users and the groups of the system. You can create or remove the users as well. Here, we are going to talk about creating several new accounts with the use of the Linux useradd command. Along with that, you will see many more functions.

How to Create User in Linux? [useradd Command]

The useradd Command

Here is the general syntax to begin with useradd command, which is Linux Create User Command:

Linux VPS

Linux VPS

The useradd command here creates a new account. It runs according to some of the default values mentioned in the /etc/default/useradd file.

Along with this, the command also runs through the /etc/login.defs file. This file imbibes certain information like the range of user IDs, password expiration policies, and much more.

To log in as a new user, you must set the user password first. How do you do that?

Simply write this command:

After you execute this command, you need to enter the details. Always set a secure password with alphanumerics.

Changing password for user username.

New password:

Retype new password:

passwd: all authentication tokens updated successfully.

Now, have a look at the list of commands to fulfill several other requirements.

How to create user Linux with a specific home directory?

The useradd command automatically creates a home directory of the user in /home. If you want to change the location, use -d option.

Now, look at the following command to create a user having /opt/username as the home directory.

sudo useradd -d /home/test_user test_user

How to creating users in Linux with a specific group ID?

When we talk about groups in Linux, they are primarily used in the administration and the usage of several user accounts.

Groups generally define certain privileges. For instance, read, write, and execute permissions. These permissions are given to a particular resource to be shared among other users.

The useradd command automatically creates a group with the name as that of the username. With the exact copy of the GID as that of the UID.

Now, -g (- -gid) helps create a user with a certain login group. You have to mention the GID number or the group name.

How to create users in Linux with a specific user ID?

As you know, the users are known by their respective UID and username.

When we talk about a User Identifier, UID, it is simply a positive integer that is allocated to every user in the Linux system. It helps to understand the different types of actions that a user can perform on the system.

In the login.defs file, a range of user IDs is mentioned. The system automatically allocates the available user identifier from this range.

To execute the command, use the following syntax:

If you further want the verification of the user UID, type this:

Читайте также:  Топ популярных линукс дистрибутивов

How to add a user in Linux and assign multiple groups?

The Linux operating system inhibits two kinds of groups. Primary group and secondary group. The secondary group is also called a supplementary group.

Every user can be assigned to only one primary group. Whereas in the case of secondary groups, the number is either zero or more.

Look at the below-stated command mentioning the primary group ‘users’ and secondary group ‘wheel’ and ‘docker.’

sudo useradd -g users -G wheel,developers username

If you want to check the user groups, type the following command:

uid=1002(username) gid=100(users) groups=100(users),10(wheel),993(docker)

How to create a new user Linux with a changed login shell?

For your information, a new user’s login shell is always set according to the one depicted in /etc/default/useradd file.

You will notice that in some cases, the default shell is /bin/sh, whereas, in others, it is specified in /bin/bash.

If you want to mention the login shell of a new user, kindly use -s (- -shell) option.

Now here is a syntax to create a user we change the login shell:

How to make user in Linux with an expiry date?

There are certain times when you would want to know the expiry date of the user accounts. To do that, use the following option: -e (- — expiredate). You can also create temporary accounts with this option.

Here is the syntax to create a user with an expiry date:

useradd -e 2021-03-05 test_user

Using this command, you can create a user with an expiry date of March 30, 2021.

If you want to verify the user account expiry date, then use the following command:

How to create a user with a comment?

In case you need to add a description for a new user, use -c (- — comment) option.

sudo useradd -c “This is a test user” test_user

How to create a user without mentioning the home directory?

To full fill this needs, type the following command:

This command helps you to create a user without a specific home directory.

How to set an unencrypted password for the user?

To set an unencrypted password, use the following command:

sudo useradd -p test_password test_user

How to create a system user?

Particularly there is no solid technical difference between a regular user and the system user. When we talk about system users, they have created while installing the operating system.

To create a system user account, use the -r (- — system) option.

For your information, the system users do not have an expiry date.

How to change the default useradd values?

You can do that using -D, (- — defaults option).

Manually, just edit the values in /etc/default/useradd file.

Use the following command to view the default option type:

How to display help?

Using the following command, you can retrieve the help section of useradd command.

Conclusion

We have presented information about using useradd command in Linux to create several user accounts. The above-stated article showcases numerous ways to make your working easier in the Linux system.

We hope the information adds value to your knowledge and widens your horizons.

Источник

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