Удаление пользователя linux ubuntu терминал

Удаляем пользователя в Linux

Рассказываем, как удалить пользователя из любого дистрибутива Linux.

Удаляем пользователей с помощью терминала

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

Используем команду deluser

Эта команда работает следующим образом:

Для работы используется базовый набор параметров, который указан в файле deluser.conf. В этом файле отображаются опции, такие как:

  • REMOVE_HOME — заставляет удалить вместе с пользователем его домашнюю директорию со всеми файлами.
  • REMOVE_ALL_FILES — заставляет удалить вместе с пользователям сразу все файлы, а не только те, что хранятся в домашней папке.
  • BACKUP — если этот параметр указан, то после удаления пользователя все его файлы будут перенесены в резервную копию.
  • BACKUP_TO — в этом параметре вписывается директория, куда будут копироваться файлы пользователя.
  • ONLY_IF_EMPTY — заставляет удалить вместе с пользователем его группу, если там больше никого нет.

Чтобы редактировать файл со стандартными опциями, можно воспользоваться любым текстовым редактором. Например, можно написать так: cat /etc/deluser.conf .

Используем команду userdel

У этой команды нет файла для настройки, но есть несколько параметров, которые можно указать прямо во время запуска команды.

Чтобы вместе с пользователем удалить еще и домашнюю директорию с ее содержимым, нужно ввести аргумент -r . Получится userdel -r имя пользователя .

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

Удаляем пользователей с помощью графической оболочки

Сейчас Linux не так сильно отличается от Windows и macOS, чтобы пользоваться исключительно терминалом. Есть привычные графические интерфейсы и программы для решения мелких задач, включая такие, как добавление и удаление пользователей. Тем не менее, я рекомендую использовать терминал, потому что он более универсальный и практичный метод управления системой.

Gnome

В системах типа Ubuntu и Debian по умолчанию установлен рабочий стол GNOME 3, — в нем есть нужная нам программа для управления пользователями.

Но даже пользователям других оболочек можно установить программу для управления пользователями из GNOME.

Источник

Как добавлять и удалять пользователей в Ubuntu 20.04

Одна из первых задач при подготовке новой системы Ubuntu — это добавление и удаление пользователей. У каждого пользователя могут быть разные уровни разрешений и определенные настройки для различных приложений командной строки и графического интерфейса.

В этой статье объясняется, как добавлять и удалять учетные записи пользователей в Ubuntu 18.04.

Подготовка

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

Новых пользователей можно создать двумя способами:

Добавление пользователя из командной строки

В Ubuntu есть два инструмента командной строки, которые вы можете использовать для создания новой учетной записи: useradd и adduser .

useradd — это утилита низкого уровня. adduser — это сценарий, написанный на Perl, который действует как дружественный интерактивный интерфейс для useradd .

Читайте также:  Shs чем открыть линукс

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

Adding user `username' . Adding new group `username' (1001) . Adding new user `username' (1001) with group `username' . Creating home directory `/home/username' . Copying files from `/etc/skel' . 

Вам будет задан ряд вопросов. Введите и подтвердите новый пароль пользователя. Ответить на все остальные вопросы необязательно.

Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully Changing the user information for username 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] 

В конце вам будет предложено подтвердить, что введенная вами информация верна.

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

Если вы хотите, чтобы новый пользователь мог выполнять административные задачи, вам необходимо добавить пользователя в группу sudo :

sudo usermod -aG sudo username

Добавление пользователя через графический интерфейс

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

  1. Откройте окно настроек и перейдите на вкладку «Пользователи».
  2. Нажмите кнопку «Разблокировать» и при появлении запроса введите пароль пользователя. После ввода пароля кнопка «Разблокировать» изменится на зеленую кнопку «Добавить пользователя».
  3. Нажмите кнопку «Добавить пользователя», появится диалоговое окно «Добавить пользователя»:
  4. Выберите, должен ли новый пользователь быть стандартным пользователем или администратором, и введите информацию. После этого нажмите кнопку «Добавить».

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

В Ubuntu вы можете использовать две команды для удаления учетной записи пользователя: userdel и его интерактивный интерфейс deluser .

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

Приведенная выше команда не удаляет пользовательские файлы.

Если вы хотите удалить пользователя, его домашний каталог и почтовый ящик, используйте флаг —remove-home :

sudo deluser --remove-home username

Удаление пользователя через графический интерфейс

  1. Откройте окно настроек и перейдите на вкладку «Пользователи».
  2. Нажмите кнопку «Разблокировать» и при появлении запроса введите пароль пользователя.
  3. Нажмите на имя пользователя, которое хотите удалить, и в правом нижнем углу вы увидите красную кнопку «Удалить пользователя …».
  4. Нажмите кнопку «Удалить пользователя …», и вам будет предложено сохранить или удалить домашний каталог пользователя. Нажатие на одну из этих кнопок удаляет пользователя.

Выводы

Мы показали вам, как добавлять и удалять пользователей в Ubuntu 20.04. Знание того, как добавлять и удалять пользователей — один из основных навыков, которые должен знать пользователь Linux.

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

Источник

How to Add and Delete Users on Ubuntu 20.04

How to Add and Delete Users on Ubuntu 20.04

Adding and removing users on a Linux system is one of the most important system administration tasks to familiarize yourself with. When you create a new system, you are often only given access to the root account by default.

While running as the root user gives you complete control over a system and its users, it is also dangerous and possibly destructive. For common system administration tasks, it’s a better idea to add an unprivileged user and carry out those tasks without root privileges. You can also create additional unprivileged accounts for any other users you may have on your system. Each user on a system should have their own separate account.

Читайте также:  Все об администрировании сервера linux

For tasks that require administrator privileges, there is a tool installed on Ubuntu systems called sudo . Briefly, sudo allows you to run a command as another user, including users with administrative privileges. In this guide, you’ll learn how to create user accounts, assign sudo privileges, and delete users.

Prerequisites

To complete this tutorial, you will need access to a server running Ubuntu 20.04. Ensure that you have root access to the server and firewall enabled. To set this up, follow our Initial Server Setup Guide for Ubuntu 20.04.

Adding a User

If you are signed in as the root user, you can create a new user at any time by running the following:

If you are signed in as a non-root user who has been given sudo privileges, you can add a new user with the following command:

Either way, you will be required to respond to a series of questions:

  • Assign and confirm a password for the new user.
  • Enter any additional information about the new user. This is optional and can be skipped by pressing ENTER if you don’t wish to utilize these fields.
  • Finally, you’ll be asked to confirm that the information you provided was correct. Press Y to continue.

Your new user is now ready for use and can be logged into with the password that you entered.

If you need your new user to have administrative privileges, continue on to the next section.

Granting a User Sudo Privileges

If your new user should have the ability to execute commands with root (administrative) privileges, you will need to give the new user access to sudo . Let’s examine two approaches to this task: first, adding the user to a pre-defined sudo user group, and second, specifying privileges on a per-user basis in sudo ’s configuration.

Adding the New User to the Sudo Group

By default, sudo on Ubuntu 20.04 systems is configured to extend full privileges to any user in the sudo group.

You can view what groups your new user is in with the groups command:

By default, a new user is only in their own group because adduser creates this in addition to the user profile. A user and its own group share the same name. In order to add the user to a new group, you can use the usermod command:

The -aG option tells usermod to add the user to the listed groups.

Please note that the usermod command itself requires sudo privileges. This means that you can only add users to the sudo group if you’re signed in as the root user or as another user that has already been added as a member of the sudo group. In the latter case, you will have to precede this command with sudo , as in this example:

Specifying Explicit User Privileges in /etc/sudoers

As an alternative to putting your user in the sudo group, you can use the visudo command, which opens a configuration file called /etc/sudoers in the system’s default editor, and explicitly specify privileges on a per-user basis.

Читайте также:  What is x client in linux

Using visudo is the only recommended way to make changes to /etc/sudoers because it locks the file against multiple simultaneous edits and performs a validation check on its contents before overwriting the file. This helps to prevent a situation where you misconfigure sudo and cannot fix the problem because you have lost sudo privileges.

If you are currently signed in as root, run the following:

If you are signed in as a non-root user with sudo privileges, run the same command with the sudo prefix:

Traditionally, visudo opened /etc/sudoers in the vi editor, which can be confusing for inexperienced users. By default on new Ubuntu installations, visudo will use the nano text editor, which provides a more convenient and accessible text editing experience. Use the arrow keys to move the cursor, and search for the line that reads like the following:

Below this line, add the following highlighted line. Be sure to change newuser to the name of the user profile that you would like to grant sudo privileges:

root ALL=(ALL:ALL) ALL newuser ALL=(ALL:ALL) ALL 

Add a new line like this for each user that should be given full sudo privileges. When you’re finished, save and close the file by pressing CTRL + X , followed by Y , and then ENTER to confirm.

Testing Your User’s Sudo Privileges

Now your new user is able to execute commands with administrative privileges.

When signed in as the new user, you can execute commands as your regular user by typing commands as normal:

You can execute the same command with administrative privileges by typing sudo ahead of the command:

When doing this, you will be prompted to enter the password of the regular user account you are signed in as.

Deleting a User

In the event that you no longer need a user, it’s best to delete the old account.

You can delete the user itself, without deleting any of their files, by running the following command as root:

If you are signed in as another non-root user with sudo privileges, you would use the following:

If, instead, you want to delete the user’s home directory when the user is deleted, you can issue the following command as root:

If you’re running this as a non-root user with sudo privileges, you would run the same command with the sudo prefix:

If you previously configured sudo privileges for the user you deleted, you may want to remove the relevant line again:

Or use the following command if you are a non-root user with sudo privileges:

root ALL=(ALL:ALL) ALL newuser ALL=(ALL:ALL) ALL # DELETE THIS LINE 

This will prevent a new user created with the same name from being accidentally given sudo privileges.

Conclusion

You should now have a fairly good handle on how to add and remove users from your Ubuntu 20.04 system. Effective user management will allow you to separate users and give them only the access that they are required to do their job.

For more information about how to configure sudo , check out our guide on how to edit the sudoers file.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

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