Delete all user in 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 a user account on Ubuntu Linux

How to delete a user account on Ubuntu

  1. Open the terminal app
  2. Login to server using the ssh user@server-ip-here command
  3. Run sudo deluser —remove-home userNameHere command to delete a user account on Ubuntu
  4. 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 (команда userdel)

How to Delete/Remove Users in Linux (userdel Command)

Это руководство охватывает userdel команду и ее параметры.

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

Иногда вам может понадобиться удалить учетную запись пользователя. Возможно, потому что пользователь отошел от организации или был создан для определенной службы, которая больше не работает в системе.

В Linux вы можете удалить учетную запись пользователя и все связанные с ней файлы с помощью userdel команды.

Синтаксис команды userdel

Синтаксис userdel команды следующий:

Чтобы удалить пользователей с помощью userdel команды, вам необходимо войти в систему как пользователь root или пользователь с правами sudo доступа.

Как удалить пользователя в Linux

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

При вызове команда читает содержимое /etc/login.defs файла. Свойства, определенные в этом файле, переопределяют поведение по умолчанию userdel . Если USERGROUPS_ENAB установлено значение yes в этом файле, userdel удаляет группу с тем же именем пользователя, только если никакой другой пользователь не является членом этой группы.

Команда удаляет запись пользователя из /etc/passwd и /etc/shadow, файлов.

В большинстве дистрибутивов Linux при удалении учетной записи userdel пользователя домашние каталоги и каталоги спула не удаляются.

Используйте параметр -r ( —remove ), чтобы принудительно userdel удалить домашний каталог пользователя и почтовую папку:

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

Если пользователь, которого вы хотите удалить, все еще вошел в систему, или если запущены процессы , принадлежащие этому пользователю, userdel команда не позволяет удалить пользователя.

В этой ситуации рекомендуется выйти из системы и завершить все запущенные процессы пользователя с помощью killall команды:

После этого вы можете удалить пользователя.

Другой вариант — использовать опцию -f ( —force ), которая предписывает userdel принудительно удалить учетную запись пользователя, даже если пользователь все еще вошел в систему или если запущены процессы, принадлежащие пользователю.

Вывод

Из этого руководства вы узнали, как удалять учетные записи пользователей в Linux с помощью userdel команды. Тот же синтаксис применяется для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian, Fedora и Arch Linux.

userdel это утилита низкого уровня, пользователи Debian и Ubuntu, скорее всего, будут использовать deluser вместо нее команду Friendlier.

Источник

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.

Источник

Читайте также:  Как сохранить уже установленные обновления windows
Оцените статью