- Как удалить пользователя в Linux
- Синтаксис
- userdel
- deluser
- Параметры утилиты лежат в файле /etc/deluser.conf
- Примеры
- Вывод
- 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 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:
Как удалить пользователя в Linux
Операционная система Linux является многопользовательской системой. Это значит, что несколько человек могут взаимодействовать с ОС. Права доступа у различных пользователей одного персонального компьютера могут быть разными. Задача системного администратора состоит в том, чтобы следить за аккаунтами пользователей, включать и исключать их из определенных групп. Но помимо этих задач может возникнуть необходимость стереть запись бывшего сотрудника с компьютера вообще.
В ОС Linux стереть юзера утилитой – userdel. Пользователи некоторых дистрибутивов могут применять более понятную команду — deluser.
Синтаксис
Для удаления пользователей в операционных системах Линукс, используются две похожие команды userdel в Centos и deluser в Debian.
userdel
- —f или —force — принудительное удаление.
- -h или —help — справочная информация.
- -r или —remove — стереть домашний каталог юзера.
- -Z или —selinux-user стереть SELinux объекты юзера.
deluser
Параметры утилиты лежат в файле /etc/deluser.conf
- REMOVE_HOME — очистить домашний каталог.
- REMOVE_ALL_FILES — очистить все файлы.
- BACKUP — бэкап файлов.
- BACKUP_TO — папка для бэкапа.
- ONLY_IF_EMPTY — очистить группу юзера при условии, что папка пустая.
Примеры
Для примера, удалим пользователя polzovatel
При выполнении, утилита обратится к login.defs, который находится по адресу /etc/login.defs. Значения, записанные в данном файле, определяют начальные опции программы userdel. Если переменная USERGROUPS_ENAB имеет значение «yes», то будет удалена группа, с пользовательским именем, которое системный администратор вбил в команду. Но при условии, что больше в этой группе нет других пользователей.
Информация о пользователе будет также удалена из файлов:
Следует учитывать то, что в большинстве дистрибутивов Linux команда userdel не стирает домашний каталог и почтовый спул пользователя.
Для того, чтобы это исправить необходимо передать параметр –r. Выглядеть такая операция будет так:
userdel –r polzovatel
Но даже в таком виде утилита не удалит файлы из других файловых систем. Сделать это придётся вручную.
Если человек, запись которого необходимо удалить, зашёл в ОС, то уничтожить его аккаунт привычным способом не получится. Здесь существует два возможных пути решения:
- Выйти из ОС и принудительно закрыть все активные юзерские программы. Для этого понадобится утилита killall – sudo killall –u polzovatel. По выполнению этой команды, можно удалять учетку пользователя.
- Передать параметр –f утилите userdel. Эта опция позволяет в принудительном режиме избавиться от аккаунта, даже если человек залогинился или имеются активные пользовательские программы.
userdel –f polzovatel
Вывод
Как видите, стереть учетку юзера в Linux очень просто. Для этого достаточно знать, как вводятся простейшие команды в терминал, и как им передавать различные параметры. Даже начинающий сисадмин с лёгкостью справится с этим.
Источник
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 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.
Источник