Linux mistakenly delete the user's home directory recovery method

  • 2020-06-12 11:42:05
  • OfStack

During production, a user's home directory may be deleted due to an error. In this case, the user's home directory will need to be installed with the same template files as when the new user was created, and restored with the same permissions as before.

1. Create 1 new user for testing


[root@centos6 aubin]# useradd wangcai

2. When the new user is created, a folder with the same name will be automatically created under /home


[root@centos6 home]# ls
aubin gentoo li wangcai

3. First, check the files and permissions in the user's home directory to verify that there is no deviation of permissions after we recover


[root@centos6 aubin]# ls /home/wangcai/ -al
total 28
drwx------. 4 wangcai wangcai 4096 Jul 24 19:11 .
drwxr-xr-x. 6 root  root  4096 Jul 24 19:11 ..
-rw-r--r--. 1 wangcai wangcai  18 Mar 23 08:15 .bash_logout
-rw-r--r--. 1 wangcai wangcai 176 Mar 23 08:15 .bash_profile
-rw-r--r--. 1 wangcai wangcai 124 Mar 23 08:15 .bashrc
drwxr-xr-x. 2 wangcai wangcai 4096 Nov 12 2010 .gnome2
drwxr-xr-x. 4 wangcai wangcai 4096 Jul 14 10:38 .mozilla

3. The home directory was deleted because of a production error


[root@centos6 home]# rm -rf wangcai/
[root@centos6 home]# ls 
aubin gentoo li  # delete wangcai directory 

4. Copy all files in skel to home. The files in the skel directory are in the home directory where the new user was created. In other words, the file in skel is the template for creating the user's home directory.


[root@centos6 home]# cp /etc/skel/ /home/wangcai -a

5. Look at the copied wangcai folder and notice that the owner and group under 1 are both root, so we need to change it to wangcai


[root@centos6 home]# ls -al
drwxr-xr-x. 4 root root 4096 Jul 14 10:49 wangcai

6. First change the permissions on the wnagcai directory to 700


[root@centos6 home]# chmod 700 wangcai/

7. Finally, the group and owner of all files in wangcai directory are changed into users themselves.

The -ES37en option is recursive, changing the Settings for all files in the directory.


[root@centos6 home]# chown wangcai:wangcai wangcai/ -R
[root@centos6 home]# ls -al wangcai/
total 28
drwxr-xr-x. 4 wangcai wangcai 4096 Jul 14 10:49 .
drwxr-xr-x. 6 root  root  4096 Jul 24 20:06 ..
-rw-r--r--. 1 wangcai wangcai  18 Mar 23 08:15 .bash_logout
-rw-r--r--. 1 wangcai wangcai 176 Mar 23 08:15 .bash_profile
-rw-r--r--. 1 wangcai wangcai 124 Mar 23 08:15 .bashrc
drwxr-xr-x. 2 wangcai wangcai 4096 Nov 12 2010 .gnome2
drwxr-xr-x. 4 wangcai wangcai 4096 Jul 14 10:38 .mozilla

At this point, the user's home directory is restored and the permissions are exactly the same as before.


Related articles: