Linux add user account

Создание пользователя в Linux. Команды adduser и useradd

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

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

Для создания пользователей из командной строки обычно используют утилиты adduser или useradd. Рассмотрим, использование данных утилит.

В чем отличия adduser и useradd?

useradd — это низкоуровневая утилита для создания пользователей в Linux.

adduser — представляет собой более простое решение для создания пользователей и по факту является надстройкой над useradd, groupadd и usermod.

Утилита adduser доступна не во всех дистрибутивах Linux. Реализация adduser также может отличаться. Если в дистрибутиве присутствует утилита adduser, то для создания пользователей рекомендуется использовать именно ее.

Команда adduser

Создание пользователя командой adduser

Рассмотрим, как создать обычного пользователя командой adduser

Чтобы создать нового пользователя, выполняем команду adduser и указываем имя пользователя (вместо pupkin укажите имя пользователя, которого вы создаете):

После запуска данной команды, вы должны ввести пароль для нового пользователя. Затем будет предложено ввести дополнительную информацию о пользователе: имя, номер комнаты (кабинета), телефоны и комментарий. Вводить эту информацию необязательно. Просто нажимайте Enter , чтобы пропустить ввод данных.

$ sudo adduser pupkin [sudo] пароль для pingvinus: Добавляется пользователь «pupkin» . Добавляется новая группа «pupkin» (1001) . Добавляется новый пользователь «pupkin» (1001) в группу «pupkin» . Создаётся домашний каталог «/home/pupkin» . Копирование файлов из «/etc/skel» . Новый пароль : Повторите ввод нового пароля : passwd: пароль успешно обновлён Изменение информации о пользователе pupkin Введите новое значение или нажмите ENTER для выбора значения по умолчанию Полное имя []: Vasiliy Pupkin Номер комнаты []: 123 Рабочий телефон []: Домашний телефон []: Другое []: Janitor Данная информация корректна? [Y/n] y

Команда adduser в Linux

В результате выполнения команды adduser будут выполнены следующие действия:

  • Создается новый пользователь с именем, которое вы указали при выполнении команды.
  • Создается группа с тем же именем.
  • Создается домашний каталог пользователя в директории /home/имяпользователя
  • В домашний каталог копируются файлы из директории /etc/skel

Команда useradd

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

Команда useradd принимает в качестве аргумента имя пользователя, а также различные опции.

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

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

Чтобы просто создать пользователя используется команда useradd без каких-либо опций. Указывается только имя пользователя.

Данная команда создает нового пользователя с системными параметрами по умолчанию, которые прописаны в файле /etc/default/useradd

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

Создание нового пользователя с домашней директорией в /home

Создадим пользователя и его домашнюю директорию.

Домашняя директория создается по умолчанию в каталоге /home . Имя директории совпадает с именем пользователя.

Создание нового пользователя с произвольной домашней директорией

Чтобы создать пользователя с домашней директорией, расположенной в произвольном месте, используется опция -d , после которой указывается путь до директории. Директорию необходимо создать заранее.

Создаем домашнюю директорию для будущего пользователя:

Копируем файлы и директории, которые по умолчанию создаются в домашней директории пользователя в данной системе. Данные файлы находятся в директории /etc/skel

sudo cp -rT /etc/skel /users/pupkin

Создаем пользователя и указываем домашнюю директорию:

sudo useradd -d /users/pupkin pupkin

Меняем права доступа у домашней директории:

sudo chown -R pupkin:pupkin /users/pupkin

Задаем пароль для пользователя:

Можно просмотреть информацию о пользователе, которая сохранена в файле /etc/passwd

cat /etc/passwd | grep pupkin pupkin:x:1001:1001::/users/pupkin:/bin/sh

Команда useradd. Создание пользователя с произвольной домашней директорией

Создание нового пользователя с произвольными UID, GID

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

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

useradd -u 1234 -g 1222 pupkin

Создание пользователя с указанием оболочки (shell)

По умолчанию новые пользователи создаются с оболочкой /bin/sh Чтобы задать другую оболочку, используется опция -s /путь/до/оболочки

sudo useradd -m -s /bin/bash pupkin

Создать пользователя и добавить его в группы

Обычно пользователи в Linux принадлежат нескольким группам. Чтобы при создании нового пользователя задать группы, к которым он будет принадлежать, используется опция -G список,групп

sudo useradd -m -G adm,cdrom,wheel -s /bin/bash pupkin

Заключение

Мы рассмотрели примеры создания нового пользователя в Linux с использованием команд adduser и useradd . Команда adduser более простая и в большинстве случаев рекомендуется использовать именно ее.

Источник

Create User Account using useradd/adduser commands in Linux

In this tutorial, you will learn how to create user account using useradd/adduser commands in Linux. User management is one of the most common task in Linux system administration. Creating users, setting up their environments, setting passwords, managing their groups, deleting users etc are all tasks surrounding user management in Linux. Having the ability to manage users in LInux is one of the most paramount basic skill in Linux administration.

Create User Account using useradd/adduser commands in Linux

Note that user account management in Linux requires elevated privileges; the use of root account or a standard account with sudo rights.

Below is what we are going to cover in regards to user account creation in Linux;

Create User Account using useradd/adduser commands in Linux

There are various way in which you can create user accounts in Linux. If you are using desktop based system, you can do user account creation from the GUI (or console if you want), while on the headless servers you can do user account creation from the console, here in called the terminal. In this tutorial, we will focus on creating user management in Linux from terminal.

Linux provides various commands for creating user accounts, with the most common ones being useradd and adduser utilities.

Create User accounts using useradd command in Linux

The command line syntax for useradd utility is;

useradd [-c comment] [-d home-dir] [-e expire-date] [-f inactive-days] [-g default-group] [-G group[. ]] [-m [-k skeleton-dir] | -M] [-p password] [-s shell] [-u UID [-o]] [-r] [-N] username

In its simplest form, you would simply run the useradd as shown below to create a user;

For example, to create an account for user johndoe;

This creates a user account with the default options defined on the /etc/login.defs file. You can view the defaults from the passwd database. The useradd command default options are also defined in /etc/default/useradd file.

johndoe:x:1002:1002::/home/johndoe:/bin/sh

By default, a group will also be created for the new user with the same group ID (GID) as user ID (UID) and same group name as username;

You can pass multiple options to the useradd utility to customize your user account during creation. For example, see the command below;

useradd -m -c "Jane Doe" -s /bin/bash -g level1 -G level1,level2 janedoe
  • -m : tells the useradd command to create user’s home directory (/home/janedoe).
  • -c : defines a short description of the user, and is currently used as the field for the user’s full name (Jane Doe).
  • -s : defines a custom user’s login shell, bash is used above. Check /etc/login.defs for the default value, usually /bin/sh
  • -g : defines a custom primary group for user instead of creating a group similar to login name (username). The group must already be existing.
  • -G : adds a user to additional groups specified. Groups must also be already existing.

To list the default options defined on the useradd defaults file, /etc/default/useradd ;

For a complete description of other command line options, refer to man useradd .

Create User account using adduser command in Linux

adduser command, unlike useradd command, helps you to interactively add user account to your linux system. You would simply execute it from your Linux terminal as follows;

For example, to create a user called janedoe;

On Debian based systems, this command will run interactively asking you about various details about the user;

Adding user `janedoe' . Adding new group `janedoe' (1002) . Adding new user `janedoe' (1001) with group `janedoe' . Creating home directory `/home/janedoe' . Copying files from `/etc/skel' . New password: Retype new password: passwd: password updated successfully Changing the user information for janedoe Enter the new value, or press ENTER for the default Full Name []: Jane Doe Room Number []: Work Phone []: Home Phone []: Other []: Is the information correct? [Y/n] y

Both adduser and useradd commands copies the initial user profile/environment settings defined under the /etc/skel directory to the user login/home directory.

By default, adduser command uses the default settings defined under /etc/adduser.conf file.

You can specify various options on the command line;

adduser --home /home/janedoe --shell /bin/bash --gecos "" janedoe

On RHEL derivatives, the adduser command is a symbolic link to useradd command and will just run non-interactively as useradd command.

lrwxrwxrwx. 1 root root 7 Nov 8 2019 /usr/sbin/adduser -> useradd

Setting User Account Password in Linux

Before a user account becomes usable, you need to have set a password for it. useradd command doesn’t prompt for password. adduser command however, prompts you to set the password.

You can set/reset user account password using passwd utility.

As as administrator/super user (root), you can set user password as simple as executing the command;

There are other account details you can control using the passwd utility. Read more on man passwd about the command line options.

As a standard user, you can only reset your own password. While resetting a password, you need to supply your old password.

With useradd command, you can specify your password on the command line using the -p ENCRYPTED_PASSWORD option.

You can generate an encrypted password using openssl or other tools such as crypt.

See example command below to use openssl with passwd command to generate encrypted password.

This will generate an hash for password password.

You can then pass this to -p option as the hash;

useradd -m -p QqjgPLfXQD8Zk username

You can simply achieve this using one command;

useradd -m -p $(openssl passwd password) username

Viewing User Account Information in Linux

  • /etc/passwd : Stores general user information such as username, user ID, group ID, location of home directory, login shell, the Geckos information. The file can be read by standard users.
  • /etc/shadow : Stores user password information such as expiry date, the password hash…The file cannot be read by standard users.

Viewing General User Account Information

To view the general user information from the passwd database, use the getent tool.

This will list all the users and their account information. If you want to view specific user account information, you can grep the user or simply pass the username as the argument.

getent passwd | grep janedoe
janedoe:x:1002:1002::/home/janedoe:/bin/bash

Viewing User Account Password Information in Linux

To view user’s password information, you can similarly read from the shadow database using the getent command.

And that is how easy it is to create and view user account information in Linux.

The commands that we used in this tutorial, supports other wide number of command line options. Be sure to check the man pages of each individual command to get a comprehensive description of these options.

That marks the end of our guide on how to create user account using useradd/adduser commands in Linux.

Reference

SUPPORT US VIA A VIRTUAL CUP OF COFFEE

We’re passionate about sharing our knowledge and experiences with you through our blog. If you appreciate our efforts, consider buying us a virtual coffee. Your support keeps us motivated and enables us to continually improve, ensuring that we can provide you with the best content possible. Thank you for being a coffee-fueled champion of our work!

Источник

Читайте также:  Пакет офисных приложений linux
Оцените статью
Adblock
detector