How to Add and Remove Users on Ubuntu 20.04
The very first task when you are provisioning a new Ubuntu system is adding and removing users. Users have different permission levels and specific settings for various GUI (Graphic User Interface) and CLI (Command Line Interface) applications.
In this journal entry, we will be having an understanding on how we can add and remove user(s) account on Ubuntu 20.04.
Before We Begin
Only root or users with sudo privileges can create and remove users.
New users can be created in two ways:
- From the command line.
- Through the GUI.
Adding a User from the Command Line
In Ubuntu, there are two command-line tools that you can use to create a new user account: useradd and adduser.
useradd is a low-level utility. adduser is a script written in Perl that acts as a friendly interactive frontend for useradd.
Adding a new user is quick and easy, simply invoke the adduser command followed by the username. For example, to create a new user account named djuser you would run:
Adding user ‘djuser’ …
Adding new group ‘djuser’ (1001) …
Adding new user ‘djuser’ (1001) with group ‘djuser’ …
Creating home directory ‘/home/djuser’ …
Copying files from ‘/etc/skel’ …
You will be asked a series of questions. Enter and confirm the new user password. Providing an answer to all other questions is optional.
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for djuser
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n]
After entering all the information, you’ll be prompted to confirm that the information you entered is correct.
The command will create the new user’s home directory, and copy files from /etc/skel to it. Within the home directory, the user can write, edit, and delete files and directories.
If you want the new user to be able to perform administrative tasks, you need to add the user to the sudo group :
Adding a User through the GUI
If CLI (Command Line Interface) is not your forte and you are more comfortable working with the GUI, then you can follow below steps:
- Open the settings window and click on the “Users” tab.
- Click on the “Unlock” button, and enter your user password when prompted.
After providing the password, the “Unlock” button will change to a green “Add User” button.
3. Click on the “Add User” button. This will open up new dialog window where we can provide the new User details.
4. You can select whether the new user will have Standard or Administrator privileges.
5. Once you are done with the information, click on the “Add” button.
Removing a User from the Command Line
In Ubuntu, you can use two commands to delete a user account: userdel and its interactive frontend deluser.
To delete the user, invoke the deluser command and pass the username as the argument:
The above command will remove the user identity but not the user files.
If you want to delete the user and its home directory and mail spool, use the — remove-home flag:
sudo deluser — remove-home djuser
Removing a User through the GUI
- Open the settings window and click on the “Users” tab.
- Click on the “Unlock” button, and enter your user password when prompted.
- Click on the username you want to delete, and you will see a red “Remove User” button on the bottom right corner.
4. Click the “Remove User” button, and you will be prompted whether to keep or delete the user home directory. Clicking on one of those buttons removes the user.
Conclusion
Adding and Removing users in a Linux environment is one of the basic skills for an Administrator/User of Linux should possess. In this journal entry, we can across the steps on how we can add and remove users in Ubuntu 20.04.
DESCRIPTION
When invoked without the -D option, the useradd command creates a new user account using the values specified on the command line plus the default values from the system. Depending on command line options, the useradd command will update system files and may also create the new user’s home directory and copy initial files.
By default, a group will also be created for the new user (see -g, -N, -U, and USERGROUPS_ENAB).
OPTIONS
The options which apply to the useradd command are:
-b, —base-dir BASE_DIR
If this option is not specified, useradd will use the base directory specified by the HOME variable in /etc/default/useradd, or /home by default.
-c, —comment COMMENT
-d, —home-dir HOME_DIR
-D, —defaults
-e, —expiredate EXPIRE_DATE
If not specified, useradd will use the default expiry date specified by the EXPIRE variable in /etc/default/useradd, or an empty string (no expiry) by default.
-f, —inactive INACTIVE
If not specified, useradd will use the default inactivity period specified by the INACTIVE variable in /etc/default/useradd, or -1 by default.
-F, —add-subids-for-system
-g, —gid GROUP
If not specified, the behavior of useradd will depend on the USERGROUPS_ENAB variable in /etc/login.defs. If this variable is set to yes (or -U/—user-group is specified on the command line), a group will be created for the user, with the same name as her loginname. If the variable is set to no (or -N/—no-user-group is specified on the command line), useradd will set the primary group of the new user to the value specified by the GROUP variable in /etc/default/useradd, or 1000 by default.
-G, —groups GROUP1[,GROUP2. [,GROUPN]]]
-h, —help
-k, —skel SKEL_DIR
This option is only valid if the -m (or —create-home) option is specified.
If this option is not set, the skeleton directory is defined by the SKEL variable in /etc/default/useradd or, by default, /etc/skel.
If possible, the ACLs and extended attributes are copied.
-K, —key KEY=VALUE
Example: -K PASS_MAX_DAYS =-1 can be used when creating an account to turn off password aging. Multiple -K options can be specified, e.g.: -K UID_MIN =100 -K UID_MAX=499
-l, —no-log-init
By default, the user’s entries in the lastlog and faillog databases are reset to avoid reusing the entry from a previously deleted user.
If this option is not specified, useradd will also consult the variable LOG_INIT in the /etc/default/useradd if set to no the user will not be added to the lastlog and faillog databases.
-m, —create-home
By default, if this option is not specified and CREATE_HOME is not enabled, no home directories are created.
The directory where the user’s home directory is created must exist and have proper SELinux context and permissions. Otherwise the user’s home directory cannot be created or accessed.
-M, —no-create-home
-N, —no-user-group
The default behavior (if the -g, -N, and -U options are not specified) is defined by the USERGROUPS_ENAB variable in /etc/login.defs.
-o, —non-unique
This option is only valid in combination with the -u option. As a user identity serves as key to map between users on one hand and permissions, file ownerships and other aspects that determine the system’s behavior on the other hand, more than one login name will access the account of the given UID.
-p, —password PASSWORD
Without this option, the new account will be locked and with no password defined, i.e. a single exclamation mark in the respective field of /etc/shadow. This is a state where the user won’t be able to access the account or to define a password himself.
Note:Avoid this option on the command line 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.
-r, —system
System users will be created with no aging information in /etc/shadow, and their numeric identifiers are chosen in the SYS_UID_MIN—SYS_UID_MAX range, defined in /etc/login.defs, instead of UID_MIN—UID_MAX (and their GID counterparts for the creation of groups).
Note that useradd will not create a home directory for such a user, regardless of the default setting in /etc/login.defs (CREATE_HOME). You have to specify the -m options if you want a home directory for a system account to be created.
Note that this option will not update /etc/subuid and /etc/subgid. You have to specify the -F options if you want to update the files for a system account to be created.
-R, —root CHROOT_DIR
-P, —prefix PREFIX_DIR
-s, —shell SHELL
-u, —uid UID
See also the -r option and the UID_MAX description.
-U, —user-group
The default behavior (if the -g, -N, and -U options are not specified) is defined by the USERGROUPS_ENAB variable in /etc/login.defs.
-Z, —selinux-user SEUSER
Changing the default values
When invoked with only the -D option, useradd will display the current default values. When invoked with -D plus other options, useradd will update the default values for the specified options. Valid default-changing options are:
-b, —base-dir BASE_DIR
This option sets the HOME variable in /etc/default/useradd.
-e, —expiredate EXPIRE_DATE
This option sets the EXPIRE variable in /etc/default/useradd.
-f, —inactive INACTIVE
This option sets the INACTIVE variable in /etc/default/useradd.
-g, —gid GROUP
This option sets the GROUP variable in /etc/default/useradd.
-s, —shell SHELL
This option sets the SHELL variable in /etc/default/useradd.
NOTES
The system administrator is responsible for placing the default user files in the /etc/skel/ directory (or any other skeleton directory specified in /etc/default/useradd or on the command line).
CAVEATS
You may not add a user to a NIS or LDAP group. This must be performed on the corresponding server.
Similarly, if the username already exists in an external user database such as NIS or LDAP, useradd will deny the user account creation request.
Usernames 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 username. Fully numeric usernames and usernames . or .. are also disallowed. It is not recommended to use usernames beginning with . character as their home directories will be hidden in the ls output.
Usernames may only be up to 32 characters long.
CONFIGURATION
The following configuration variables in /etc/login.defs change the behavior of this tool:
CREATE_HOME (boolean)
This setting does not apply to system users, and can be overridden on the command line.
GID_MAX (number), GID_MIN (number)
The default value for GID_MIN (resp. GID_MAX) is 1000 (resp. 60000).
HOME_MODE (number)
useradd and newusers use this to set the mode of the home directory they create.
LASTLOG_UID_MAX (number)
No LASTLOG_UID_MAX option present in the configuration means that there is no user ID limit for writing lastlog entries.
MAIL_DIR (string)
MAIL_FILE (string)
The MAIL_DIR and MAIL_FILE variables are used by useradd, usermod, and userdel to create, move, or delete the user’s mail spool.
MAX_MEMBERS_PER_GROUP (number)
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.
PASS_MAX_DAYS (number)
PASS_MIN_DAYS (number)
PASS_WARN_AGE (number)
SUB_GID_MIN (number), SUB_GID_MAX (number), SUB_GID_COUNT (number)
The default values for SUB_GID_MIN, SUB_GID_MAX, SUB_GID_COUNT are respectively 100000, 600100000 and 65536.
SUB_UID_MIN (number), SUB_UID_MAX (number), SUB_UID_COUNT (number)
The default values for SUB_UID_MIN, SUB_UID_MAX, SUB_UID_COUNT are respectively 100000, 600100000 and 65536.
SYS_GID_MAX (number), SYS_GID_MIN (number)
The default value for SYS_GID_MIN (resp. SYS_GID_MAX) is 101 (resp. GID_MIN-1).
SYS_UID_MAX (number), SYS_UID_MIN (number)
The default value for SYS_UID_MIN (resp. SYS_UID_MAX) is 101 (resp. UID_MIN-1).
UID_MAX (number), UID_MIN (number)
The default value for UID_MIN (resp. UID_MAX) is 1000 (resp. 60000).
UMASK (number)
useradd and newusers use this mask to set the mode of the home directory they create if HOME_MODE is not set.
Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7d99e937588d22f5 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Как создать пользователя 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 — отобразить параметры, которые используются по умолчанию для создания пользователя. Если вместе с этой опцией задать еще какой-либо параметр, то его значение по умолчанию будет переопределено.
Теперь, когда вы знаете основные необходимые нам параметры утилиты мы можем перейти к разбору того, как выполняется создание нового пользователя linux. Сначала давайте посмотрим какие параметры будут применены для пользователя по умолчанию:
Как видите, по умолчанию домашний каталог пользователя будет создан в /home и будет использоваться оболочка /bin/sh. Теперь создадим минимального пользователя с минимальными настройками:
sudo useradd test
Был создан самый простой пользователь, без оболочки и пароля, а также без групп. Теперь немного усложним задачу и создадим пользователя с паролем и оболочкой /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.