How to delete user in linux
How to delete user in linux
How to Delete User Accounts with Home Directory in Linux
In this tutorial, I am going to take your through steps you can use to delete a user’s account together with his/her home directory on a Linux system.
Delete User Accounts with Home Directory in Linux
To learn how to create user accounts and manage them on Linux systems, read the following articles from the links below:
As a System Administrator in Linux, you may have to remove users account at after sometime when a user account may become dormant for so long, or user may leave the organization or company or any other reasons.
When removing user accounts on a Linux system, it is also important to remove their home directory to free up space on the storage devices for new system users or other services.
Deleting/Removing a User Account with His/Her Home Directory
1. For demonstration purpose, first I will start by creating two user accounts on my system that is user tecmint and user linuxsay with their home directories /home/tecmint and /home/linusay respectively using adduser command.
Create New User Accounts in Linux
From the screenshot above, I have used the adduser command to create user accounts on Linux. You can also use useradd command, both are same and does the same job.
2. Let’s now move further to see how to delete or remove user accounts in Linux using deluser (For Debian and it’s derivatives) and userdel (For RedHat/CentOS based systems) command.
The directives inside the configuration file for deluser and userdel commands determine how this it will handle all user files and directory when you run the command.
Let us look at the configuration file for the deluser command which is /etc/deluser.conf on Debian derivatives such as Ubuntu, Kali, Mint and for RHEL/CentOS/Fedora users, you can view the /etc/login.defs files.
The values in the these configuration are default and can be changed as per your needs.
3. To delete a user with home directory, you can use the advanced way by following these steps on your Linux server machine. When users are logged on to the server, they use services and run different processes. It is important to note that user can only be deleted effectively when they are not logged on to the server.
Lock User Accounts in Linux
Start by locking the user account password so that there is no access for the user to the system. This will prevent a user from running processes on the system.
The passwd command including the –lock option can help you achieve this:
Lock User Account Password in Linux
Find and Kill All Running Processes of User
Next find out all running processes of user account and kill them by determine the PIDs (Process IDs) of processes owned by the user using:
Then you can list the processes interms of username, PIDs, PPIDs (Parent Process IDs), terminal used, process state, command path in a full formatting style with the help of following command as shown:
Find All Running Processes of User
Once you find all the running processes of user, you can use the killall command to kill those running processes as shown.
The -9 is the signal number for the SIGKILL signal or use -KILL instead of -9 and -u defines username.
Note: In recent releases of RedHat/CentOS 7.x versions and Fedora 21+, you will get error message as:
To fix such error, you need to install psmisc package as shown:
Backup User Data Before Deleting
Next you can backup users files, this can be optional but it is recommended for future use when need arises to review user account details and files.
I have used the tar utilities to create a backup of users home directory as follows:
Backup User Home Directory in Linux
Delete/Remove User Account and Files
Delete User Account with Home Directory
Summary
That is all to do with removing user and their home directory from a Linux system. I believe the guide is easy enough to follow, but you can voice a concern or add more idea by leaving a comment.
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.
Как удалить пользователя в Linux
В этой инструкции мы рассмотрим как удалить пользователя Linux вместе с его данными и домашним каталогом. Если вы системный администратор в крупной компании то, скорее всего, удаление пользователей Linux для вас довольно частая задача. После того как аккаунт становится ненужным или пользователь ушел из организации, его аккаунт нужно удалить, чтобы не оставлять дыр в безопасности.
Что нам понадобится?
Перед тем как переходить к действиям в реальной среде нужно немного попрактиковаться, давайте создадим два пользователя losst и losst1, вместе с домашними каталогами, а затем уже будем их удалять:
adduser losst
passwd losst
adduser losst1
passwd losst1
Здесь команда adduser используется для создания учетной записи пользователя, а passwd для создания пароля.
Удаление пользователя Linux в терминале
Описание deluser
Синтаксис команды deluser очень простой:
$ deluser параметры пользователь
Настройки команды deluser находятся в файле /etc/deluser.conf, среди прочих настроек там указанно что нужно делать с домашней папкой и файлами пользователя. Вы можете посмотреть и изменить эти настройки выполнив команду:
Рассмотрим подробнее эти настройки:
Эти настройки определяют поведение утилиты по умолчанию, когда выполняется удаление пользователя, конечно, их можно переопределить используя параметры для команды.
Поддерживаются такие параметры, они аналогичны настройкам, но тут больше вариантов:
Описание userdel
Утилита userdel работает немного по-другому, файла настроек здесь нет, но есть опции, с помощью которых можно сообщить утилите что нужно сделать. Синтаксис аналогичный:
$ userdel параметры пользователь
Для удаления пользователя с сервера лучше использовать расширенный способ, который мы рассмотрим ниже. Когда пользователи используют сервер, они запускают различные программы и сервисы. Пользователь может быть правильно удален, только если он не залогинен на сервере и все программы, запущенные от его имени остановлены, ведь программы могут использовать различные файлы, принадлежащие пользователю, а это помешает их удалить. Соответственно тогда файлы пользователя будут удаленны не полностью и останутся засорять систему.
Блокировка учетной записи пользователя
Уничтожить все запущенные процессы пользователя
Теперь давайте найдем все запущенные от имени пользователя процессы и завершим их. Найдем процессы с помощью pgrep:
Посмотреть подробнее, что это за процессы можно передав pid, каждого из них в команду ps, вот так:
Теперь, когда вы убедились, что там нет ничего важного, можно уничтожить все процессы с помощью команды killall:
В основанных на Red Hat системах, для использования killall необходимо будет установить пакет psmisc:
sudo yum install psmisc
Резервное копирование данных пользователя
Это вовсе не обязательно, но для серьезного проекта не будет лишним создать резервную копию файлов пользователя, особенно если там могли быть важные файлы. Для этого можно использовать, например, утилиту tar:
tar jcvf /user-backups/losst-backup.tar.bz2 /home/losst
Удаление учетной записи пользователя
Теперь, когда все подготовлено, начинаем удаление пользователя linux. На всякий случай укажем явно, что нужно удалять файлы пользователя и домашнюю директорию. Для Debian:
Если нужно удалить все файлы, принадлежащие пользователю в системе используйте опцию —remove-all-files, только будьте с ней осторожны, так и важные файлы можно затереть:
Теперь пользователь полностью удален, вместе со своими файлами и домашней директорией из вашей системы.
Удаление пользователя в Ubuntu
Как я и говорил, дальше рассмотрим как удалить пользователя в Ubuntu с помощью графического интерфейса. Это намного проще того, что было описано выше, но менее эффективнее.
Откройте Параметры системы:
Откройте пункт Пользователи:
Как видите, сейчас все действия недоступны, и нарисованы серым цветом. Чтобы их активировать нажмите кнопку Разблокировать и введите пароль пользователя.
Теперь для того чтобы удалить пользователя в linux достаточно кликнуть по нему мышкой, а затем нажать внизу страницы нажать кнопку Удалить пользователя:
В открывшимся окне можно выбрать, что нужно сделать с файлами пользователя:
Естественно, будет удаленна только домашняя папка, обо всех файлах речь не идет. И для корректного удаления пользователь должен быть не залогинен в системе.
Выводы
Удалить пользователя в Linux не так уж сложно, независимо от того где это нужно сделать, на сервере или домашнем компьютере. Конечно, графический интерфейс более удобен, но в терминал, как всегда, предлагает больше возможностей. Если у вас есть еще какие-нибудь идеи по этому поводу, напишите в комментариях!
How to Add and Delete Users on Ubuntu 18.04
Introduction
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.
Prerequisites
To complete this tutorial, you will need access to a server running Ubuntu 18.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 18.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:
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
Adding the New User to the Sudo Group
By default, sudo on Ubuntu 18.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:
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.
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:
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:
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 18.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.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Linux Delete User
By Priya Pedamkar
Introduction to Linux Delete User
Linux Delete user option is used to delete a user from Server. By deleting a user form Linux, we can remove SSH access also and delete user’s files and user ownership directories. We can delete users in Linux only if we have root permissions.
Basic Syntax:
Web development, programming languages, Software testing & others
Linux server is a server where multiple users can login at a time. This means that there will be a number of users created and interacted at the same time. To manage their accounts, the administration should take up the responsibility to manage the user’s account. There might be situations where we would need to delete a user from the Server because the user is no longer associated with the organization or the user is no longer running in the server. Here in this article, we will discuss how to delete a user from the server.
Syntax
The following are the ways that are used to delete a user from Server. The syntax is below:
Here the below options are used with userdel command in Linux:
How to Delete a User from Linux?
Below are the options that we can use to perform the delete operation on a user in Server.
Options | Description |
-f | Forcefully delete a user account and also with forceful removal of files. |
-r | Deletes user account along with mail spool and user’s home directory |
-z | Deletes SELinux users if they are mapped for the users while deleting user from Linux. |
Follow the below process step by step to delete a user in Linux:
How To Delete / Remove Users in Linux Using the userdel Command
As a Linux system administrator, one of the primary responsibility is to manage the users and groups on Linux systems. User management includes creating users, modifying existing users and deleting users.
Deleting / Removing a user account is the most important task for an administrator when any user leaves from an organization.
This post explains to you how to delete users in Linux using the userdel command.
Prerequisites
To be able to delete/remove a user account, you need to be logged in as a root user or a user with sudo privileges.
userdel command
In Linux, you can delete a user account with userdel command. The userdel command is a low-level utility which is used for removing user accounts in Linux and other Unix like operating systems.
Syntax:
How To Delete / Remove User in Linux
To delete a user called user_name from Linux system, use:
Consider checking additional activities you may need to perform before you delete a user account in Linux.
How To Delete / Remove User with Home Directory in Linux
In most of the distributions, the userdel command will not delete the user’s home directory and mail spool.
Additional Activities Before Deleting User
Running the userdel command looks like super easy, but the system won’t let you delete the user account if the user is logged in or any process running on his/her name.
Output:
Kill the user’s running process with the killall command. This command will also kick the user out of the system.
Lock the user so that the user will not be able to log in again.
You can consider taking the backup of the user’s home directory for future needs.
Conclusion
You have learned how to delete user accounts in Linux using the userdel command. Do double check the user name before you delete users from Linux system.