误删大文件的一个可能解救办法

上周在一台 OpenNebula 服务器上操作虚拟机镜像,正在生成和比对镜像文件的 md5 指纹:

# ls -l test.img
-rw-r--r-- 1 root root 10486808576 Oct 12 02:21 test.img

# md5sum test.img

在另一个窗口清理文件的时候不小心误删了这个 10GB 左右的镜像文件:

# rm test.img

这时候行动迅速的话还有时间拯救,因为服务器繁忙,执行 rm 删除 10GB 大文件的时候需要一点时间,利用这点时间切换到另一窗口使用 Ctrl+Z 立刻暂停 md5sum:

[1]+  Stopped                 md5sum test.img

这里利用的一个原理就是,如果有其他程序正在使用这个文件的话,Linux 不会真正删除这个文件(即使执行了 rm 命令)。我们在删除命令 rm 执行完之前暂停 md5sum,这样 test.img 就一直会被 md5um 占用而不会真正被 rm 删除。

使用 jobs 可以看到被暂停的 md5sum 的进程号 30888,然后查看这个进程打开了哪些文件:

# jobs -l
[1]+ 30888 Stopped                 md5sum test.img

# ls -l /proc/30888/fd
total 0
lrwx------ 1 root root 64 Oct 22 04:04 0 -> /dev/pts/3
lrwx------ 1 root root 64 Oct 22 04:04 1 -> /dev/pts/3
lrwx------ 1 root root 64 Oct 22 04:04 2 -> /dev/pts/3
lr-x------ 1 root root 64 Oct 22 04:04 3 -> /root/test.img (deleted)

使用 cp 就可以把误删的文件拷贝出来:

# cp /proc/30888/fd/3 save.img
# ls -l save.img
-rw-r--r-- 1 root root 10486808576 Oct 22 06:11 save.img

误删文本文件的话可以尝试用 grep 恢复,误删 exe/doc/png/jpg/gif 之类的文件的话,可以用第三方 ext2/ext3 文件恢复工具 TestDisk, PhotoRec 等帮助恢复文件。

评论 (5 Comments)

  1. 既然cp可以,那ln可不可以呢?谁能试一下

  2. ln 不可以,不能 ln 一个已删除的文件。

  3. 这个比较巧合…正好有一个程序在调用该文件….实际情况下很少会碰到…

  4. 看来还是要养成习惯,用mv /tmp

  5. 那么用了clean my mac 做了一次清理之后能不能回复呢?

发表评论