- How To Delete Remove User Accounts In Linux?
- List Existing Accounts
- Remove/Delete User Account with userdel Command
- Remove/Delete User Account and Home Directory
- Remove/Delete User Account with Home Directory and User Owned Files
- Remove/Delete User Account Line From passwd File
- How to Delete User Accounts with Home Directory in Linux
- Deleting/Removing a User Account with His/Her Home Directory
- Lock User Accounts in Linux
- Find and Kill All Running Processes of User
- Backup User Data Before Deleting
- Delete/Remove User Account and Files
- Summary
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- How To: Linux Delete / Remove User Account Using userdel
- Linux delete user command syntax
- userdel command examples
- A Note About /etc/login.defs File
- Complete example to remove user account from Linux
- See also:
- How to delete a user account on Ubuntu Linux
- How to delete a user account on Ubuntu
- Ubuntu delete user account command
- How to verify that user has been deleted from Ubuntu
- Как удалить пользователя в Linux
- Что нам понадобится?
- Удаление пользователя Linux в терминале
- Описание deluser
- Описание userdel
- Блокировка учетной записи пользователя
- Уничтожить все запущенные процессы пользователя
- Резервное копирование данных пользователя
- Удаление учетной записи пользователя
- Удаление пользователя в Ubuntu
- Выводы
How To Delete Remove User Accounts In Linux?
How can I remove a Linux user account from Linux system. As you know user management in Linux requires root privileges. While removing user his home directory can be remove or preserved. As same with mail box. User mailbox can be preserved.
List Existing Accounts
Before removing or deleting an user account checking the existing of account can be useful. We can check whether given account exist with different ways. In this example we will use chage command with -l list option for user ismail .
- chage will give information about specified user
- -l test will list users information
- As said before the user is removed so there is no information about the user.
Or we can print the /etc/passwd in a formatted manner which only list user account names by using cut command
List Existing Accounts
Remove/Delete User Account with userdel Command
We can remove given user account with userdel command like below. In this example we will remove user account named ismail . As this is an administrative task we need root privileges which can be get with sudo command.
- userdel will remove specified test user account
Remove/Delete User Account and Home Directory
The default behavior of the userdel command is removing user account from user data which resides /etc/passwd . This will not delete the user account home directory. If we want to remove the user account home directory while removing account with userdel we should provide the -r option. In this example we will delete the user account test and its home directory.
Remove/Delete User Account with Home Directory and User Owned Files
In previous example we have deleted user account with its home directory. If we want to delete also user owned files and folders while remove user account we can use userdel command with -f option. In this example we will remove user account ali and its home folder and owned files and folders those resides other than his home directory.
Remove/Delete User Account Line From passwd File
We have an other less structured option to remove a user account. We can remove the line which user is defined from file /etc/passwd . As this file contains user details this will remove user account. We can also remove password hash from /etc/shadow .
Источник
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
Now you can safely remove user together with his/her home directory, to remove all user files on the system use the —remove-all-files option in the command below:
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.
Источник
How To: Linux Delete / Remove User Account Using userdel
H ow do I remove a user’s access from my server? How do I delete a user account under Linux operating systems include home directory and running cron jobs?
You need to use the userdel command to delete a user account and related files from user account under Linux operating system. The userdel command must be run as root user on Linux.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Linux |
Est. reading time | 4 minutes |
Linux delete user command syntax
The syntax is as follows to remove a user account on Linux.
userdel userName
userdel [options] userName
userdel -r userName
userdel command examples
Let us remove the user named vivek or account named vivek from the local Linux system / server / workstation, enter:
# userdel vivek
Next, delete the user’s home directory and mail spool pass the -r option to userdel for a user named ashish, enter:
# userdel -r ashish
Explains how to delete user account with home directory in Linux
A Note About /etc/login.defs File
Default values are taken from the information provided in the /etc/login.defs file for RHEL (Red Hat) based distros. Debian and Ubuntu Linux based system use /etc/deluser.conf file:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Complete example to remove user account from Linux
The following is recommend procedure to delete a user from the Linux server. First, lock user account, enter:
# passwd -l vivek
OR set the date on which the user account will be disabled (syntax is usermod —expiredate YYYY-MM-DD userNameHere ):
# usermod —expiredate 1 vivek
If user try to login, he or she will get the following message:
Next, backup files from /home/vivek to /nas/backup
# tar -zcvf /nas/backup/account/deleted/v/vivek.$uid.$now.tar.gz /home/vivek/
Please replace $uid, $now with actual UID and date/time. Tye userdel command will not allow you to remove an account if the user is currently logged in. You must kill any running processes which belong to an account that you are deleting, enter:
# pgrep -u vivek
# ps -fp $(pgrep -u vivek)
# killall -KILL -u vivek
Delete at jobs, enter
# find /var/spool/at/ -name «[^.]*» -type f -user vivek -delete
Remove cron jobs, enter:
# crontab -r -u vivek
Delete print jobs, enter:
# lprm vivek
To find all files owned by user vivek, enter:
# find / -user vivek -print
You can find file owned by a user called vivek and change its ownership as follows:
# find / -user vivek -exec chown newUserName:newGroupName <> \;
Finally, delete user account called vivek, enter:
# userdel -r vivek
Sample session:
Fig.01: Delete User Accounts with Home Directory and All Data In Linux
See also:
- Help: Old Employees Accessing The Linux Server.
- /etc/passwd – The basic attributes of users.
- /etc/shadow – The basic attributes of users password.
- /etc/group – The basic attributes of groups.
- Man pages – ps(1)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to delete a user account on Ubuntu Linux
How to delete a user account on Ubuntu
- Open the terminal app
- Login to server using the ssh user@server-ip-here command
- Run sudo deluser —remove-home userNameHere command to delete a user account on Ubuntu
- Verify it by running id command
Let us see all commands in details to remove a user account in Ubuntu.
Ubuntu delete user account command
Say you would like to delete a user named ubuntu, run:
$ sudo deluser —remove-home ubuntu
If you want to backup files before removing user account, try:
## create a dir to store backups ##
$ sudo mkdir /oldusers-data
$ sudo chown root:root /oldusers-data
$ sudo chmod 0700 /oldusers-data
$ sudo deluser —remove-home —backup-to /oldusers-data/ ubuntu
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How to verify that user has been deleted from Ubuntu
Use the id command or grep command as follows:
$ id ubuntu
$ grep ‘^ubuntu’ /etc/passwd
Источник
Как удалить пользователя в Linux
В этой инструкции мы рассмотрим как удалить пользователя Linux вместе с его данными и домашним каталогом. Если вы системный администратор в крупной компании то, скорее всего, удаление пользователей Linux для вас довольно частая задача. После того как аккаунт становится ненужным или пользователь ушел из организации, его аккаунт нужно удалить, чтобы не оставлять дыр в безопасности.
При удалении пользователей Linux также важно удалить их домашний каталог, чтобы освободить место на устройстве хранения для новых пользователей и их файлов. Сначала мы рассмотрим как удалить пользователя Linux с помощью терминала, потом поговорим о том, как это делается в графическом интерфейсе одного из самых популярных дистрибутивов — Ubuntu.
Что нам понадобится?
Перед тем как переходить к действиям в реальной среде нужно немного попрактиковаться, давайте создадим два пользователя losst и losst1, вместе с домашними каталогами, а затем уже будем их удалять:
adduser losst
passwd losst
adduser losst1
passwd losst1
Здесь команда adduser используется для создания учетной записи пользователя, а passwd для создания пароля.
Удаление пользователя Linux в терминале
Давайте рассмотрим, как удалить пользователя Linux в терминале. Для этого используется команда — deluser в Debian и производных системах, а в RHEL — userdel. Рассмотрим подробнее эти две утилиты.
Описание deluser
Синтаксис команды deluser очень простой:
$ deluser параметры пользователь
Настройки команды deluser находятся в файле /etc/deluser.conf, среди прочих настроек там указанно что нужно делать с домашней папкой и файлами пользователя. Вы можете посмотреть и изменить эти настройки выполнив команду:
Рассмотрим подробнее эти настройки:
- REMOVE_HOME — удалять домашний каталог пользователя
- REMOVE_ALL_FILES — удалить все файлы пользователя
- BACKUP — выполнять резервное копирование файлов пользователя
- BACKUP_TO — папка для резервного копирования
- ONLY_IF_EMPTY — удалить группу пользователя если она пуста.
Эти настройки определяют поведение утилиты по умолчанию, когда выполняется удаление пользователя, конечно, их можно переопределить используя параметры для команды.
Поддерживаются такие параметры, они аналогичны настройкам, но тут больше вариантов:
- —system — удалять только если это системный пользователь
- —backup — делать резервную копию файлов пользователя
- —backup-to — папка для резервных копий
- —remove-home — удалять домашнюю папку
- —remove-all-files — удалять все файлы пользователя в файловой системе
Описание userdel
Утилита userdel работает немного по-другому, файла настроек здесь нет, но есть опции, с помощью которых можно сообщить утилите что нужно сделать. Синтаксис аналогичный:
$ userdel параметры пользователь
- -f, —force — принудительное удаление, даже если пользователь еще залогинен.
- -r, —remove — удалить домашнюю директорию пользователя и его файлы в системе.
- -Z — удалить все SELinux объекты для этого пользователя.
Для удаления пользователя с сервера лучше использовать расширенный способ, который мы рассмотрим ниже. Когда пользователи используют сервер, они запускают различные программы и сервисы. Пользователь может быть правильно удален, только если он не залогинен на сервере и все программы, запущенные от его имени остановлены, ведь программы могут использовать различные файлы, принадлежащие пользователю, а это помешает их удалить. Соответственно тогда файлы пользователя будут удаленны не полностью и останутся засорять систему.
Блокировка учетной записи пользователя
Для блокировки учетной записи пользователя можно использовать утилиту passwd. Это запретит пользователю доступ к системе и предотвратит запуск новых процессов. Выполните команду passwd с параметром —lock:
passwd —lock losst
Уничтожить все запущенные процессы пользователя
Теперь давайте найдем все запущенные от имени пользователя процессы и завершим их. Найдем процессы с помощью pgrep:
Посмотреть подробнее, что это за процессы можно передав pid, каждого из них в команду ps, вот так:
ps -f —pid $(pgrep -u losst)
Теперь, когда вы убедились, что там нет ничего важного, можно уничтожить все процессы с помощью команды killall:
Killall -9 -u losst
Опция -9 говорит программе, что нужно отправить этим процессам сигнал завершения SIGKILL, а -u задает имя пользователя.
В основанных на Red Hat системах, для использования killall необходимо будет установить пакет psmisc:
sudo yum install psmisc
Резервное копирование данных пользователя
Это вовсе не обязательно, но для серьезного проекта не будет лишним создать резервную копию файлов пользователя, особенно если там могли быть важные файлы. Для этого можно использовать, например, утилиту tar:
tar jcvf /user-backups/losst-backup.tar.bz2 /home/losst
Удаление учетной записи пользователя
Теперь, когда все подготовлено, начинаем удаление пользователя linux. На всякий случай укажем явно, что нужно удалять файлы пользователя и домашнюю директорию. Для Debian:
deluser —remove-home losst
userdel —remove losst
Если нужно удалить все файлы, принадлежащие пользователю в системе используйте опцию —remove-all-files, только будьте с ней осторожны, так и важные файлы можно затереть:
deluser —remove-all-files losst
Теперь пользователь полностью удален, вместе со своими файлами и домашней директорией из вашей системы.
Удаление пользователя в Ubuntu
Как я и говорил, дальше рассмотрим как удалить пользователя в Ubuntu с помощью графического интерфейса. Это намного проще того, что было описано выше, но менее эффективнее.
Откройте Параметры системы:
Откройте пункт Пользователи:
Как видите, сейчас все действия недоступны, и нарисованы серым цветом. Чтобы их активировать нажмите кнопку Разблокировать и введите пароль пользователя.
Теперь для того чтобы удалить пользователя в linux достаточно кликнуть по нему мышкой, а затем нажать внизу страницы нажать кнопку Удалить пользователя:
В открывшимся окне можно выбрать, что нужно сделать с файлами пользователя:
Естественно, будет удаленна только домашняя папка, обо всех файлах речь не идет. И для корректного удаления пользователь должен быть не залогинен в системе.
Выводы
Удалить пользователя в Linux не так уж сложно, независимо от того где это нужно сделать, на сервере или домашнем компьютере. Конечно, графический интерфейс более удобен, но в терминал, как всегда, предлагает больше возможностей. Если у вас есть еще какие-нибудь идеи по этому поводу, напишите в комментариях!
Источник