百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Linux下用rm误删除文件的三种恢复方法

ahcoder 2025-01-16 17:32 9 浏览

对于rm,很多人都有惨痛的教训。我也遇到一次,一下午写的程序就被rm掉了,幸好只是一个文件,第二天很快又重新写了一遍。但是很多人可能就不像我这么幸运了。本文收集了一些在Linux下恢复rm删除的文件的方法,给大家作为参考。

1.几点建议避免误删

 首先,最好的方法是避免这个问题,以下是几点建议:

  1、rm -rf误操作的后果是可怕的,rm -f也要三思而行,不能轻易使用。

  2、做好数据备份。

  3、用一些策略避免出错:

  提倡在shell下用 TAB 补全,用脚本执行任务,减少出错的机会。或者编写一个脚本,起名rm,在脚本里将真实的rm改为mv ,将删除的都mv到一个指定的目录里面,定期清理。

  那么rm删除的文件还能恢复吗?

  rm的man里面有如下说法:

  请注意,如果使用 rm 来删除文件,通常仍可以将该文件恢复原状。如果想保证该文件的内容无法还原,请考虑使用 shred。

  所以理论上rm删除的文件是还能恢复的。删掉文件其实只是将指向数据块的索引点(information nodes)释放,只要不被覆盖,数据其实还在硬盘上,关键在于找出索引点,然后将其所指数据块内的数据抓出,再保存到另外的分区。在用rm误删除文件后,我们要做的第一件事就是保证不再向误删文件的分区写数据。

2.使用lsof命令恢复

lsof命令用于查看你进程开打的文件,打开文件的进程,进程打开的端口(TCP、UDP)。找回/恢复删除的文件。是十分方便的系统监视工具,因为lsof命令需要访问核心内存和各种文件,所以需要root用户执行。

在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件。所以如传输控制协议 (TCP) 和用户数据报协议 (UDP) 套接字等,系统在后台都为该应用程序分配了一个文件描述符,无论这个文件的本质如何,该文件描述符为应用程序与基础操作系统之间的交互提供了通用接口。因为应用程序打开文件的描述符列表提供了大量关于这个应用程序本身的信息,因此通过lsof工具能够查看这个列表对系统监测以及排错将是很有帮助的。

1.语法

lsof(选项)

2.参数

-a:列出打开文件存在的进程; 
-c<进程名>:列出指定进程所打开的文件; 
-g:列出GID号进程详情; 
-d<文件号>:列出占用该文件号的进程; 
+d<目录>:列出目录下被打开的文件; 
+D<目录>:递归列出目录下被打开的文件; 
-n<目录>:列出使用NFS的文件; 
-i<条件>:列出符合条件的进程。(4、6、协议、:端口、 @ip ) 
-p<进程号>:列出指定进程号所打开的文件; 
-u:列出UID号进程详情; 
-h:显示帮助信息; 
-v:显示版本信息。

3.使用

查看

lsof -i:(端口) 查看这个端口有那些进程在访问,比如22端口

shell> lsof -i:22
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd     1939 root    3u  IPv4  12317      0t0  TCP *:ssh (LISTEN)
sshd     1939 root    4u  IPv6  12321      0t0  TCP *:ssh (LISTEN)
sshd     2790 root    3u  IPv4  15229      0t0  TCP 192.168.178.128:ssh->192.168.178.1:64601 (ESTABLISHED)
sshd     2824 root    3u  IPv4  15528      0t0  TCP 192.168.178.128:ssh->192.168.178.1:64673 (ESTABLISHED)
sshd     2990 root    3u  IPv4  15984      0t0  TCP 192.168.178.128:ssh->192.168.178.1:64686 (ESTABLISHED)
sshd    14695 root    3u  IPv4  39558      0t0  TCP 192.168.178.128:ssh->192.168.178.1:49662 (ESTABLISHED)

lsof输出各列信息的意义如下:

  • COMMAND:进程的名称
  • PID:进程标识符
  • USER:进程所有者
  • FD:文件描述符,应用程序通过文件描述符识别该文件。如cwd、txt等
  • TYPE:文件类型,如DIR、REG等
  • DEVICE:指定磁盘的名称
  • SIZE:文件的大小
  • NODE:索引节点(文件在磁盘上的标识)
  • NAME:打开文件的确切名称

恢复文件

利用lsof可以恢复一些系统日志,前提是这个进程必须存在。这里就拿最常用的/var/log/messages来举例说明,大家在做测试的时候最好先备份一下。

#备份
shell> cp /var/log/message /var/log/message_bac

shell> lsof |grep /var/log/message
rsyslogd   1737      root    1w      REG                8,2   5716123     652638 /var/log/messages

进程在运行中,接下来我就把/var/log/messages这个文件删掉

shell> rm /var/log/messages

删掉之后,我再来看看这个进程的变化

shell> lsof |grep /var/log/messages
rsyslogd   1737      root    1w      REG                8,2   5716123     652638 /var/log/messages (deleted)

大家看到有变化了吧, 对比两个之后发现多了(deleted)。要找到这个文件在哪还要看看这个

PID:1737 FD:1 那我们有直接进入/proc/1737/FD/1用ll查看一下

shell> cd /proc/1737/fd/
shell> ll

total 0
lrwx------ 1 root root 64 Dec 23 13:00 0 -> socket:[11442]
l-wx------ 1 root root 64 Dec 23 13:00 1 -> /var/log/messages (deleted)
l-wx------ 1 root root 64 Dec 23 13:00 2 -> /var/log/secure
lr-x------ 1 root root 64 Dec 23 13:00 3 -> /proc/kmsg
l-wx------ 1 root root 64 Dec 23 13:00 4 -> /var/log/maillog

看到了1对应/var/log/messages (deleted),看看文件是不是我们要的文件:

shell> head -5 1
Nov 14 03:11:11 localhost kernel: imklog 5.8.10, log source = /proc/kmsg started.
Nov 14 03:11:11 localhost rsyslogd: [origin software="rsyslogd" swVersion="5.8.10" x-pid="1241" x-info="http://www.rsyslog.com"] start
Nov 14 03:11:11 localhost kernel: Initializing cgroup subsys cpuset
Nov 14 03:11:11 localhost kernel: Initializing cgroup subsys cpu
Nov 14 03:11:11 localhost kernel: Linux version 2.6.32-431.el6.x86_64 (mockbuild@c6b8.bsys.dev.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) ) #1 SMP Fri Nov 22 03:15:09 UTC 2013

对比备份文件:

shell> head -5 /var/log/message_bac
Nov 14 03:11:11 localhost kernel: imklog 5.8.10, log source = /proc/kmsg started.
Nov 14 03:11:11 localhost rsyslogd: [origin software="rsyslogd" swVersion="5.8.10" x-pid="1241" x-info="http://www.rsyslog.com"] start
Nov 14 03:11:11 localhost kernel: Initializing cgroup subsys cpuset
Nov 14 03:11:11 localhost kernel: Initializing cgroup subsys cpu
Nov 14 03:11:11 localhost kernel: Linux version 2.6.32-431.el6.x86_64 (mockbuild@c6b8.bsys.dev.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) ) #1 SMP Fri Nov 22 03:15:09 UTC 2013

对比发现数据是一样的,恢复

shell> cat 1 > /var/log/messages

再次提醒,恢复前提是这个进程必须存在。

3.使用extundelete工具

extundelete工具安装

  • extundelete下载地址:http://extundelete.sourceforge.net/
wget https://nchc.dl.sourceforge.net/project/extundelete/extundelete/0.2.4/extundelete-0.2.4.tar.bz2

解压该文件tar jxvf extundelete-0.2.4.tar.bz2

若报这种错误

[root@docking ~]# tar jxvf extundelete-0.2.4.tar.bz2 
tar (child): bzip2:无法 exec: 没有那个文件或目录
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now

则使用yum -y install bzip2进行解决

[root@docking ~]# tar jxvf extundelete-0.2.4.tar.bz2 
extundelete-0.2.4/
extundelete-0.2.4/acinclude.m4
extundelete-0.2.4/missing
extundelete-0.2.4/autogen.sh
extundelete-0.2.4/aclocal.m4
extundelete-0.2.4/configure
extundelete-0.2.4/LICENSE
extundelete-0.2.4/README
...................................................
cd  extundelete-0.2.4
./configure 

若这步骤报错

[root@docking extundelete-0.2.4]# ./configure 
Configuring extundelete 0.2.4
configure: error: in `/root/extundelete-0.2.4':
configure: error: C++ compiler cannot create executables
See `config.log' for more details

则使用yum -y install gcc-c++解决.

若执行上一步仍然报错,

[root@docking extundelete-0.2.4]# ./configure 
Configuring extundelete 0.2.4
configure: error: Can't find ext2fs library

则使用yum -y install e2fsprogs e2fsprogs-devel来解决。
#Ubuntu的解决办法为sudo apt-get install e2fslibs-dev e2fslibs-dev

不出意外的话到这里应该configure能够顺利完成.

[root@docking extundelete-0.2.4]# ./configure 
Configuring extundelete 0.2.4
Writing generated files to disk
[root@docking extundelete-0.2.4]# 

最后make然后 make install

[root@docking extundelete-0.2.4]# make
make -s all-recursive
Making all in src
extundelete.cc: 在函数‘ext2_ino_t find_inode(ext2_filsys, ext2_filsys, ext2_inode*, std::string, int)’中:
extundelete.cc:1272:29: 警告:在 {} 内将‘search_flags’从‘int’转换为较窄的类型‘ext2_ino_t {aka unsigned int}’ [-Wnarrowing]
    buf, match_name2, priv, 0};
                             ^
[root@docking extundelete-0.2.4]# make install
Making install in src
  /usr/bin/install -c extundelete '/usr/local/bin'

extundelete安装完成.


扫描误删除的文件:

使用df -lh查看挂载:

taroballs@taroballs-PC:~$ df -lh
文件系统        容量  已用  可用 已用% 挂载点
udev            1.9G     0  1.9G    0% /dev
tmpfs           387M  1.8M  385M    1% /run
/dev/sda2        92G   61G   26G   71% /
tmpfs           1.9G   49M  1.9G    3% /dev/shm
tmpfs           5.0M  4.0K  5.0M    1% /run/lock
tmpfs           1.9G     0  1.9G    0% /sys/fs/cgroup
/dev/sda3       104G   56G   44G   57% /home
tmpfs           387M   40K  387M    1% /run/user/1000
/dev/sda4        70G   20G   47G   30% /media/taroballs/d8423f8c-d687-4c03-a7c8-06a7fb57f96d
/dev/sdb1       6.8G  4.1G  2.8G   60% /media/taroballs/taroballs
/dev/sr0        4.0G  4.0G     0  100% /media/taroballs/2018-01-16-12-36-00-00
taroballs@taroballs-PC:~$ cd /media/taroballs/taroballs/
taroballs@taroballs-PC:/media/taroballs/taroballs$ 

可以看到,我们的目录/media/taroballs/taroballs
挂载到/dev/sdb1 这个文件系统中.


umount我们的挂载盘
比如:

taroballs@taroballs-PC:~$ df -lh | grep /dev/sdb1
/dev/sdb1       6.8G  4.1G  2.8G   60% /media/taroballs/taroballs

umount这个目录

taroballs@taroballs-PC:~$ umount /media/taroballs/taroballs
taroballs@taroballs-PC:~$ df -lh | grep /dev/sdb1
taroballs@taroballs-PC:~$ 
#记得删除一定要后umount哦,不然二次写入谁也帮不了你呢。

通过inode节点恢复

taroballs@taroballs-PC:~$ mkdir recovertest
taroballs@taroballs-PC:~$ cd recovertest/
taroballs@taroballs-PC:~/recovertest$ 

执行恢复extundelete /dev/sdb1 --inode 2

taroballs@taroballs-PC:/media/taroballs/taroballs$ sudo extundelete /dev/sdb1 --inode 2
NOTICE: Extended attributes are not restored.
Loading filesystem metadata ... 8 groups loaded.
Group: 0
Contents of inode 2:
 
.
.省略N行
 
File name                                       | Inode number | Deleted status
.                                                 2
..                                                2
deletetest                                        12             Deleted
tmppasswd                                            14             Deleted

通过扫描发现了我们删除的文件夹,现在执行恢复操作。
(1)恢复单一文件tmppasswd

taroballs@taroballs-PC:~/recovertest$  extundelete /dev/sdb1 --restore-file passwd   
NOTICE: Extended attributes are not restored.
Loading filesystem metadata ... 8 groups loaded.
Loading journal descriptors ... 46 descriptors loaded.
Successfully restored file tmppasswd

恢复文件是放到了当前目录RECOVERED_FILES。
查看恢复的文件:

taroballs@taroballs-PC:~/recovertest$ cat tmppasswd 
tcpdump:x:172:72::/:/sbin/nologin

(2)恢复目录deletetest

extundelete /dev/sdb1 --restore-directory  deletetest
NOTICE: Extended attributes are not restored.
Loading filesystem metadata ... 8 groups loaded.
Loading journal descriptors ... 46 descriptors loaded.
Searching for recoverable inodes in directory deletetest ... 
5 recoverable inodes found.
Looking through the directory structure for deleted files ... 

(3)恢复所有

taroballs@taroballs-PC:~/recovertest$ extundelete /dev/sdb1 --restore-all
NOTICE: Extended attributes are not restored.
Loading filesystem metadata ... 8 groups loaded.
Loading journal descriptors ... 46 descriptors loaded.
Searching for recoverable inodes in directory / ... 
5 recoverable inodes found.
Looking through the directory structure for deleted files ... 
0 recoverable inodes still lost. 
taroballs@taroballs-PC:~/recovertest$ tree 
backuptest/
├── deletetest
│   └── innerfolder
│       └── deletefile.txt
└── tmppasswd

2 directories, 2 files

(4)恢复指定inode

taroballs@taroballs-PC:~/recovertest$ extundelete /dev/sdb1 --restore-inode 14
NOTICE: Extended attributes are not restored.
Loading filesystem metadata ... 8 groups loaded.
Loading journal descriptors ... 46 descriptors loaded.
taroballs@taroballs-PC:~/recovertest$ cat file.14 
tcpdump:x:172:72::/:/sbin/nologin
#注意恢复inode的时候,恢复 出来的文件名和之前不一样,需要单独进行改名。

最后附上extundelete的用法:

$ extundelete --help
Usage: extundelete [options] [--] device-file
Options:
  --version, -[vV]       Print version and exit successfully.
  --help,                Print this help and exit successfully.
  --superblock           Print contents of superblock in addition to the rest.
                         If no action is specified then this option is implied.
  --journal              Show content of journal.
  --after dtime          Only process entries deleted on or after 'dtime'.
  --before dtime         Only process entries deleted before 'dtime'.
Actions:
  --inode ino            Show info on inode 'ino'.
  --block blk            Show info on block 'blk'.
  --restore-inode ino[,ino,...]
                         Restore the file(s) with known inode number 'ino'.
                         The restored files are created in ./RECOVERED_FILES
                         with their inode number as extension (ie, file.12345).
  --restore-file 'path'  Will restore file 'path'. 'path' is relative to root
                         of the partition and does not start with a '/'
                         The restored file is created in the current
                         directory as 'RECOVERED_FILES/path'.
  --restore-files 'path' Will restore files which are listed in the file 'path'.
                         Each filename should be in the same format as an option
                         to --restore-file, and there should be one per line.
  --restore-directory 'path'
                         Will restore directory 'path'. 'path' is relative to the
                         root directory of the file system.  The restored
                         directory is created in the output directory as 'path'.
  --restore-all          Attempts to restore everything.
  -j journal             Reads an external journal from the named file.
  -b blocknumber         Uses the backup superblock at blocknumber when opening
                         the file system.
  -B blocksize           Uses blocksize as the block size when opening the file
                         system.  The number should be the number of bytes.
  --log 0                Make the program silent.
  --log filename         Logs all messages to filename.
--log D1=0,D2=filename   Custom control of log messages with comma-separated
   Examples below:       list of options.  Dn must be one of info, warn, or
   --log info,error      error.  Omission of the '=name' results in messages
   --log warn=0          with the specified level to be logged to the console.
   --log error=filename  If the parameter is '=0', logging for the specified
                         level will be turned off.  If the parameter is
                         '=filename', messages with that level will be written
                         to filename.
   -o directory          Save the recovered files to the named directory.
                         The restored files are created in a directory
                         named 'RECOVERED_FILES/' by default.

相关推荐

Linux基础运维篇:Linux日志管理(第013课)

日志是什么Linux系统中的日志就像是一个记录员,它会把系统中发生的各种事情都记录下来,比如系统什么时候启动了、哪些用户登录了系统、运行了哪些程序、程序有没有出错、硬件有没有问题等等。这些记录对于系...

目标取代deb包格式,深度Linux操作系统公布“如意玲珑”项目

IT之家7月16日消息,7月13日,在上海站的deepinMeetup如意玲珑专场上,深度操作系统官方正式宣布了项目全新的品牌名称——如意玲珑(Linyaps)。目前如意玲珑已...

基于 Linux 快速搭建私有化 Helm Chart 仓库(ChartMuseum 实战指南)

一、前言在Kubernetes中,Helm是最流行的包管理工具,用于简化应用部署与管理。如果你希望在内网环境中部署、管理自己的HelmCharts,就需要搭建一个私有化HelmChart...

Linux环境开发效率--那些强大的命令

之前写了一篇关于linux下常用的几个命令,参考Linux入门--提高工作效率的命令。接下来接着介绍一些在linux下做开发经常使用到得命令,其中有打包压缩命令tar,文件查找命令find,文件内容查...

怎么使用再生龙打包(备份)liunx系统

liunx系统区别于Windows,由于分区格式的特殊性并不能像GHOST那样进行备份封包,有款开源的针对liunx系统备份还原的软件-再生龙(clonezilla),可能有部分人已经用过,本篇文章让...

python打包那些事儿(python的打包)

python是个万金油,什么活都能干,开发一些小应用的时候,要想其他人也方便使用,就需要对程序进行打包生成可执行文件,不再依赖python环境或者其他文件。前几天写了一个视频去水印的小程序,主要依赖f...

「项目部署」使用Jenkins一键打包部署SpringBoot应用

前言嗨,大家好,我是希留,一个被迫致力于全栈开发的老菜鸟。一般而言,一个项目部署的由:拉取代码->构建->测试->打包->部署等过程组成,如果我们经常需要部署项目,特别是在微服...

Linux面试最高频的5个基本问题(linux面试题必会题目)

CPU利用率和CPU负载的区别是什么提到CPU利用率,就必须理解时间片。什么是CPU时间片?我们现在所使用的Windows、Linux、MacOS都是“多任务操作系统”,就是说他们可以“同时”运行多...

jtti:如何将Linux服务器的文件系统创建成镜像

如何将Linux服务器的文件系统创建成镜像?如何把Linux文件系统创建成一个镜像文件,也就是"系统打包"?这类操作不仅适用于迁移、备份,还能用于批量部署、自定义系统安装,甚至可以作为...

用Nuitka打包 Python,效果竟如此惊人!

使用Python开发一个程序后,将Python脚本打包成独立可执行文件是一项常见需求。Nuitka是一个Python到C的编译器,它会将Python代码转换为等效的C代码,然后使用标...

Linux基础运维篇:Linux软件包管理(第014课)

什么是软件包管理在Linux系统中,软件包管理就像是一个“软件管家”,负责软件的安装、卸载、更新以及软件之间依赖关系的处理。它把软件及其相关的文件、配置信息等打包在一起,方便用户进行管理和操作。...

给你的Nodejs后端项目打个包(node为基础的后端框架)

前阵子,碰到个问题用Nodejs做了个小项目需要交付客户使用之前Nodejs做的都是自用,所以也没碰到需要打包保护源码之类的问题上网搜了半天,找到的大多是针对Vue的前端项目打包/混淆,例如用...

爆强!直接把 Python 编写的图形程序打包为安卓 APP

请大家多多关注点赞哦如果想使用Python语言编写图形界面程序,那么有不少的框架可以提供支持,比如Tkinter、QtforPython、WxPython等等。不过这些框架都是只能创建桌面图...

几行代码教你zip打包(打包zip命令)

01准备有时我们不想去手动一个个去操作,然后傻等他打包完,python依赖库zipfile很方便地帮助我们封装了解压压缩,shutil用于文件目录处理,方法类似于linux命令。1、安装pipin...

Linux基础运维篇:Linux文件操作超详细版(第007课)

一、Linux文件系统基础1.文件类型Linux一切皆文件,常见文件类型:普通文件(-):文本文件(.txt)、二进制文件(可执行程序)、压缩文件等。目录文件(d):用于组织文件和子目录(类似...