How to create user in linux
How to create user in linux
Как создать пользователей в Linux (команда useradd)
How to Create Users in Linux (useradd Command)
В этой статье мы поговорим о том, как создавать новые учетные записи пользователей с помощью useradd команды.
Useradd команда
Общий синтаксис useradd команды выглядит следующим образом:
Только root или пользователи с привилегиями sudo могут использовать useradd команду для создания новых учетных записей пользователей.
При вызове useradd создает новую учетную запись пользователя в соответствии с параметрами, указанными в командной строке, и значениями по умолчанию, установленными в /etc/default/useradd файле.
Переменные, определенные в этом файле, отличаются от распределения к распределению, что приводит к тому, что useradd команда выдает разные результаты в разных системах.
useradd также читает содержимое /etc/login.defs файла. Этот файл содержит конфигурацию для набора теневых паролей, такую как политика истечения срока действия пароля, диапазоны идентификаторов пользователей, используемых при создании системных и обычных пользователей, и многое другое.
Как создать нового пользователя в Linux
Чтобы создать новую учетную запись пользователя, вызовите useradd команду с именем пользователя.
Например, чтобы создать нового пользователя с именем, username вы должны выполнить:
Чтобы войти в систему как только что созданный пользователь, вам необходимо установить пароль пользователя. Для этого выполните passwd команду с именем пользователя:
Вам будет предложено ввести и подтвердить пароль. Убедитесь, что вы используете надежный пароль.
Как добавить нового пользователя и создать домашний каталог
В большинстве дистрибутивов Linux при создании новой учетной записи useradd пользователя домашний каталог пользователя не создается.
Приведенная выше команда создает домашний каталог нового пользователя и копирует файлы из /etc/skel каталога в домашний каталог пользователя. Если вы перечислите файлы в /home/username каталоге, вы увидите файлы инициализации:
Внутри домашнего каталога пользователь может писать, редактировать и удалять файлы и каталоги.
Создание пользователя с определенным домашним каталогом
Вот пример, показывающий, как создать нового пользователя с именем username в домашнем каталоге /opt/username :
Создание пользователя с определенным идентификатором пользователя
В Linux и Unix-подобных операционных системах пользователи идентифицируются по уникальному UID и имени пользователя.
По умолчанию при создании нового пользователя система назначает следующий доступный UID из диапазона идентификаторов пользователей, указанных в login.defs файле.
Вы можете проверить UID пользователя, используя id команду:
Создание пользователя с определенным идентификатором группы
При создании нового пользователя стандартным поведением useradd команды является создание группы с тем же именем, что и имя пользователя, и тем же GID, что и UID.
В следующем примере показано, как создать нового пользователя с именем username и задать для группы входа users тип:
Чтобы проверить GID пользователя, используйте id команду:
Создание пользователя и назначение нескольких групп
В операционных системах Linux существует два типа групп: основная группа и дополнительная (или дополнительная) группа. Каждый пользователь может принадлежать ровно к одной первичной группе и к нулю или нескольким вторичным группам.
Вы можете проверить группы пользователей, набрав
Создание пользователя с определенной оболочкой входа
Например, чтобы создать нового пользователя username с /usr/bin/zsh именем типа оболочки входа в систему:
Проверьте запись пользователя в /etc/passwd файле, чтобы проверить оболочку входа пользователя:
Создание пользователя с пользовательским комментарием
В следующем примере мы создаем нового пользователя username с текстовой строкой Test User Account в качестве комментария:
Комментарий сохраняется в /etc/passwd файле:
Создание пользователя с датой истечения срока действия
Дата должна быть указана в YYYY-MM-DD формате.
Например, чтобы создать новую учетную запись с именем username expirey, установленным на 22 января 2019 года, вы должны выполнить:
Используйте chage команду для проверки срока действия учетной записи пользователя:
Вывод будет выглядеть примерно так:
Создание пользователя системы
Нет реальной технической разницы между системой и обычными (обычными) пользователями. Обычно системные пользователи создаются при установке ОС и новых пакетов.
Пользователи системы создаются без срока действия. Их UID выбираются из диапазона системных идентификаторов пользователей, указанных в login.defs файле, который отличается от диапазона, используемого для обычных пользователей.
Изменение значений по умолчанию для useradd
Чтобы просмотреть текущие параметры по умолчанию, введите:
Вывод будет выглядеть примерно так:
Вы можете проверить, что значение оболочки по умолчанию изменено, выполнив следующую команду:
Вывод
Мы показали вам, как создавать новые учетные записи пользователей с помощью useradd команды. Те же инструкции применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian, Fedora и Arch Linux.
The Complete Guide to “useradd” Command in Linux – 15 Practical Examples
We all are aware of the most popular command called ‘useradd‘ or ‘adduser‘ in Linux. There are times when a Linux System Administrator is asked to create user accounts on Linux with some specific properties, limitations, or comments.
In Linux, a ‘useradd‘ command is a low-level utility that is used for adding/creating user accounts in Linux and other Unix-like operating systems. The ‘adduser‘ is much similar to the useradd command because it is just a symbolic link to it.
useradd command examples
In some other Linux distributions, the useradd command may come with a slightly different version. I suggest you read your documentation, before using our instructions to create new user accounts in Linux.
When we run the ‘useradd‘ command in the Linux terminal, it performs the following major things:
Useradd Command Syntax
The Basic syntax of the useradd command is:
In this article, we will show you the most used 15 useradd commands with their practical examples in Linux. We have divided the section into two parts from Basic to Advance usage of the command.
1. How to Add a New User in Linux
To add/create a new user, you’ve to follow the command ‘useradd‘ or ‘adduser‘ with ‘username‘. The ‘username‘ is a user login name, that is used by a user to login into the system.
Only one user can be added and that username must be unique (different from other usernames already exists on the system).
For example, to add a new user called ‘tecmint‘, use the following command.
When we add a new user in Linux with the ‘useradd‘ command it gets created in a locked state and to unlock that user account, we need to set a password for that account with the ‘passwd‘ command.
Create User in Linux
Once a new user is created, its entry is automatically added to the ‘/etc/passwd‘ file. The file is used to store the user’s information and the entry should be.
View User Info in Linux
The above entry contains a set of seven colon-separated fields, each field has its own meaning. Let’s see what are these fields:
2. Create a User with Different Home Directory
By default ‘useradd‘ command creates a user’s home directory under /home directory with a username. Thus, for example, we’ve seen above the default home directory for the user ‘tecmint‘ is ‘/home/tecmint‘.
However, this action can be changed by using the ‘-d‘ option along with the location of the new home directory (i.e. /data/projects). For example, the following command will create a user ‘anusha‘ with a home directory ‘/data/projects‘.
You can see the user home directory and other user-related information like user id, group id, shell, and comments.
Create User with Home Directory in Linux
3. Create a User with a Specific User ID
In Linux, every user has its own UID (Unique Identification Number). By default, whenever we create a new user account in Linux, it assigns userid 500, 501, 502, and so on…
But, we can create users with custom userid with the ‘-u‘ option. For example, the following command will create a user ‘navin‘ with custom userid ‘1002‘.
Now, let’s verify that the user created with a defined userid (1002) using the following command.
Create User with the User ID in Linux
NOTE: Make sure the value of a user ID must be unique from any other already created users on the system.
4. Create a User with a Specific Group ID
Similarly, every user has their own GID (Group Identifier). We can create users with specific group IDs as well with the -g option.
Here in this example, we will add a user ‘tarunika‘ with a specific UID and GID simultaneously with the help of ‘-u‘ and ‘-g‘ options.
Now, see the assigned user id and group id in ‘/etc/passwd‘ file.
To verify the user’s GID, use the id command:
Create User with Group ID in Linux
5. Add a User to Multiple Groups
The ‘-G‘ option is used to add a user to additional groups. Each group name is separated by a comma, with no intervening spaces.
Here in this example, we are adding a user ‘tecmint‘ into multiple groups like admins, webadmin, and developer.
Next, verify that the multiple groups are assigned to the user with the id command.
Add User to Group in Linux
6. Add a User without Home Directory
In some situations, where we don’t want to assign home directories for a user, due to some security reasons. In such a situation, when a user logs into a system that has just restarted, its home directory will be root. When such a user uses the su command, its login directory will be the previous user’s home directory.
To create users without their home directories, ‘-M‘ is used. For example, the following command will create a user ‘shilpi‘ without a home directory.
Now, let’s verify that the user is created without a home directory, using the ls command.
Create User Without Home Directory in Linux
7. Create a User with Account Expiry Date
By default, when we add user’s with the ‘useradd‘ command user account never get expires i.e their expiry date is set to 0 (means never expired).
However, we can set the expiry date using the ‘-e‘ option, which sets the date in YYYY-MM-DD format. This is helpful for creating temporary accounts for a specific period of time.
Here in this example, we create a user ‘aparna‘ with account expiry date i.e. 27th August 2021 in YYYY-MM-DD format.
Next, verify the age of the account and password with the ‘chage‘ command for user ‘aparna‘ after setting the account expiry date.
Create User With Account Expiry Date
8. Create a User with Password Expiry Date
The ‘-f‘ argument is used to define the number of days after a password expires. A value of 0 inactive the user account as soon as the password has expired. By default, the password expiry value set to -1 means never expire.
Here in this example, we will set an account password expiry date i.e. 45 days on a user ‘mansi‘ using ‘-e‘ and ‘-f‘ options.
Create User With Password Expiry Date
9. Add a User with Custom Comments
The ‘-c‘ option allows you to add custom comments, such as the user’s full name, phone number, etc to /etc/passwd file. The comment can be added as a single line without any spaces.
For example, the following command will add a user ‘mansi‘ and would insert that user’s full name, Manis Khurana, into the comment field.
You can see your comments in the ‘/etc/passwd‘ file in the comments section.
Create User with Full Name
10. Create User Login Shell in Linux
Sometimes, we add users who have nothing to do with the login shell or sometimes we require to assign different shells to our users. We can assign different login shells to each user with the ‘-s‘ option.
Here in this example, will add a user ‘tecmint‘ without login shell i.e. ‘/sbin/nologin‘ shell.
You can check the assigned shell to the user in the ‘/etc/passwd‘ file.
Create User with Login Shell
11. Add a User with Specific Home Directory, Default Shell, and Custom Comment
The following command will create a user ‘ravi‘ with home directory ‘/var/www/tecmint‘, default shell /bin/bash and adds extra information about the user.
Create User with Home Directory and Login Shell
12. Add a User with Home Directory, Custom Shell, Custom Comment, and UID/GID
The command is very similar to above, but here we defining shell as ‘/bin/zsh‘ and custom UID and GID to a user ‘tarunika‘. Where ‘-u‘ defines the new user’s UID (i.e. 100) and whereas ‘-g‘ defines GID (i.e. 1000).
Create User with UID and GID
13. Add a User with Home Directory, No Shell, Custom Comment, and User ID
The following command is very much similar to the above two commands, the only difference is here, that we disabling the login shell to a user called ‘avishek‘ with a custom User ID (i.e. 1019).
Here ‘-s‘ option adds the default shell /bin/bash, but in this case we set login to ‘/usr/sbin/nologin‘. That means user ‘avishek‘ will not able to login into the system.
Create User with UID and Nologin
14. Add a User with Home Directory, Shell, Custom Skell/Comment, and User ID
The only change in this command is, we used ‘-k‘ option to set the custom skeleton directory i.e. /etc/custom.skell, not the default one /etc/skel. We also used ‘-s‘ option to define different shell i.e. /bin/tcsh to user ‘navin‘.
Create User with Shell and UID
15. Add a User without Home Directory, No Shell, No Group, and Custom Comment
The following command is very different than the other commands explained above. Here we used the ‘-M‘ option to create a user without the user’s home directory and the ‘-N‘ argument is used that tells the system to only create a username (without group). The ‘-r‘ argument is for creating a system user.
Create User with NoLogin and Group
For more information and options about useradd, run the ‘useradd‘ command on the terminal to see available options.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Create User in Linux
By Priya Pedamkar
Introduction to Create User in Linux
In these, we will learn to create a User in Linux. What made Linux a developer’s favorite kernel. But before that, one important thing you must know before proceeding further is the fact that Linux is not an Operating System rather a Kernel. A kernel is the most important part of an operating system, but a kernel alone can’t make the OS work. OS requires other software to be working with the kernel. In the case of Linux, it’s gonna be GNU software. Linux is famous because of it’s free, open-source and provides great control over the OS.
User in Linux
Linux has a multiuser option that means more than one user can use Linux at the same time. Managing multiple users is the job of the system administrator. System Admin can add or remove a user. So, if you are a system admin, continue reading to know how to add a user to your Linux system.
Web development, programming languages, Software testing & others
Types of Adding a User to Linux
There are two ways of adding a user in Linux
1. Create a User from the shell/terminal
This way is used by most professionals and experienced Linux users. To add a user from the shell/terminal following steps have to be followed. It’s also should be your priority to give great attention to the syntax given in the step and follow them exactly.
Step 1: Open the shell or terminal.
Step 3: After getting the root access, type “useradd username”.
Step 4: Type “password username”, the terminal will ask for a new password. Confirm the new password. Enter the new password.
Step 5: You should be able to see the new user on To confirm, type “cat /etc/password”, you should be able to see your new username over there.
2. Create a User from GUI
This way of creating a user is very easy and used when you are not that familiar with Linux.
Step 1: Go to Applications and select System Settings.
Step 2: Click on User Accounts.
Step 3: At the top right corner, find the Dialog of User.
Step 4: The system will ask for Admin’s password, type incorrect password, and Dialog should be unlocked if it says it’s locked; click on it to unlock.
Step 5: After unlocking the dialog, find an add user button at the left bottom of the box, click on it.
Step 6: Type in the name of your account to be created. You can also choose the Account Type, either Standard or Admin.
Step 7: Click on Add, and you should be able to see your username on the left tab of the box.
Conclusion
Hey, congrats on knowing how to create/add a user on Linux. Multi-user access is one of the great advantages of using Linux, and you have learned the first step of it. You can add as many users as you want but remember to keep your passwords strong enough; for more educational posts, follow educba.
Recommended Articles
This is a guide to Create User in Linux. Here we discuss a step-by-step creation of a user in Linux in two forms: shell/terminal user and GUI user. You can also go through our other related articles to learn more-
Linux Training Program (16 Courses, 3+ Projects)
How To Create Users in Linux Using useradd / adduser Command
If you are a Linux system admin who administers Linux servers, you are very frequently asked to create users in Linux unless the organization uses LDAP. As a Linux administrator, you should be well versed with creating and removing users, assigning users to different groups in Linux.
This post explains to you how to create users in Linux using the useradd / adduser command.
Prerequisites
To be able to create a user account, you need to be logged in as a root user or a user with sudo privileges.
useradd command
In Linux, you can create user accounts with useradd / adduser command. The useradd command is a low-level utility which is used for creating user accounts in Linux and other Unix like operating systems.
The adduser command is just a symbolic link to useradd, so it will work similar to useradd command.
Syntax:
When then the useradd command is issued, the useradd command creates a new user account using options specified by you in the command line and default values specified in /etc/default/useradd file.
Also, the useradd command edits /etc/passwd, /etc/shadow and /etc/group to put an entry of user details and configurations (User and Group IDs, password policies, encryption method), by reading the contents of /etc/login.defs file.
Create a New User in Linux
To create a new user called user_name using the useradd command, run.
The username must be unique. Otherwise, the system would go through an error that the user name already exists.
Set a password for the newly created account with passwd command to log in to the system with that user.
You will now be prompted to enter and confirm the password.
Output:
Create a User with Home Directory
As I said earlier, the home directory for a new user may or may not be created when we use the useradd command with no options.
The above command creates the home directory /home/user_name for user user_name and copies files from /etc/skel directory to the user’s home directory.
Output:
Create a User with Specific Home Directory
Create a User with Specific User ID
In Linux, users are identified by UID (Unique Identification Number). By default, whenever the user is created in Linux, the system assigns the next available UID from the range of user IDs between UID_MIN and UID_MAX in the /etc/login.defs file.
Verify that the user’s UID is 9999 using the id command.
Output:
Create a User with Specific Group
Users are often grouped together with the Linux group. The Linux groups help us to define privileges like read, write or execute to all users within that group for a particular resource. Linux group has its own identification number GID.
When a useradd command is executed without any options, it creates a group with the same as the username and same GID as UID.
Group Name
Verify that the user’s GID is 500 using the id command.
Output:
Create a User and Add to Multiple Groups
A comma must separate group names.
Syntax:
Group Name
Verify the groups the user belongs to using the id command.
Output:
Create a User with an Expiry Date
This option is useful when you want to create a temporary user who will have access to the system only for a period of time. By default, when a useradd command issued without any options, the user will be created with account never expire value.
To create a new user user_name with an expiry date set to May 1st, 2019, you can use.
Verify the user’s expiration date using the chage command.
Output:
Create a User with Specific Login Shell
By default, when a useradd command issued without any options, the user will be created with /bin/bash (RHEL) or /bin/sh (Debian / Ubuntu) shell.
Verify the user’s login shell by reading the /etc/passwd file.
Output:
Create a User and Add Comment To User
Check the comment we added for this user.
Output:
Conclusion
I hope you have learned how to create users in Linux using useradd command. The post explained every single option you can use with the useradd command; however, you can combine options to get the desired results.
Please share your feedback in the comments section.
Как создать пользователя Linux
Основу управления правами доступа в Linux и уровнем привилегий в Linux составляют именно пользователи. Изначально, еще при проектировании системы существовал пользователь root, которому позволено выполнять любые действия и другие пользователи, права которых настраиваются с помощью вступления их в группы Linux и установки прав на каталоги.
Многопользовательская архитектура, одна из первых особенностей Linux, которая существует еще с зарождения системы. В системе могут работать одновременно множество пользователей благодаря удаленному входу, а также пользователи используются для запуска определенных сервисов. В этой статье мы рассмотрим как создать пользователя linux, рассмотрим способ через терминал и в графическом интерфейсе.
Создание пользователя в Linux
Вся информация о пользователях находится в файле /etc/passwd. Мы могли бы создать пользователя linux просто добавив его туда, но так делать не следует, поскольку для этой задачи существуют специальные утилиты. Одна из таких утилит, это useradd. Рассмотрим ее подробнее.
Команда useradd
Это довольно простая команда, которая есть во всех дистрибутивах Linux. Она позволяет зарегистрировать нового пользователя или изменить информацию об уже имеющемся. Во время создания можно даже создать домашний каталог пользователя и скопировать в него системные файлы. Рассмотрим синтаксис команды:
$ useradd опции имя_пользователя
Все довольно просто, дальше нам нужно рассмотреть основные опции команды, с помощью которых вы будете настраивать нового пользователя:
Теперь, когда вы знаете основные необходимые нам параметры утилиты мы можем перейти к разбору того, как выполняется создание нового пользователя linux. Сначала давайте посмотрим какие параметры будут применены для пользователя по умолчанию:
Как видите, по умолчанию домашний каталог пользователя будет создан в /home и будет использоваться оболочка /bin/sh. Теперь создадим минимального пользователя с минимальными настройками:
sudo useradd test
Был создан самый простой пользователь, без оболочки и пароля, а также без групп. Теперь немного усложним задачу и создадим пользователя с паролем и оболочкой /bin/bash:
Также, можно установить дату, когда аккаунт пользователя будет отключен автоматически, это может быть полезно для пользователей, которые будут работать временно:
Некоторых пользователей интересует создание пользователя с правами root linux, это очень просто делается с помощью useradd, если комбинировать правильные опции. Нам всего лишь нужно разрешить создавать пользователя с неуникальным uid, установить идентификатор в 0 и идентификатор основной группы тоже в 0. Команда будет выглядеть вот так:
Пожалуй, это все основные примеры как добавить пользователя linux. Дальше нам осталось взглянуть только на работу в графическом интерфейсе.
Создание нового пользователя linux в GUI
В графическом интерфейсе системы создать нового пользователя linux еще проще. Рассмотрим окружение Gnome, хотя и в KDE тоже есть аналогичная функция. Войдите в главное меню и откройте параметры системы:
Затем откройте «Пользователи»:
Поскольку утилита запущена от имени обычного пользователя вы ничего не можете сделать. Поэтому нажмите кнопку «Разблокировать»:
Только после этого используйте кнопку со знаком плюс для создания нового пользователя Linux:
После этого создание пользователя linux завершено, новый пользователь появится в списке.
Выводы
В этой статье мы рассмотрели как создать пользователя linux с помощью терминала или в графическом интерфейсе системы. Оба способа имеют свои преимущества. Например, способ в терминале намного гибче, но в то же время графический способ дает больше контроля над процессом. Если у вас остались вопросы, спрашивайте в комментариях!