Linux - Using debugfs to Recover Deleted File

debugfs is a very useful tool to debug ext2/ext3/ext4 file system. If your file is deleted, it could be possible to recover it via debugfs if the file's file descriptor is still be opened by some process.

Disclaimer: debugfs is some low level process that could be used to examine and modify the underlying file system. That also means, any mistake may trash your file system.

Prerequisite

1. Check whether the file descriptor is still being opened by some process

cat /proc/locks | grep {pid}  -- this will list the locks holds by {pid}

ls -al /proc/{pid}/fd/  -- this will list the file descriptor currently opened by {pid}

Note: You could use ps -ef to display the pid of the desired process.

2. Identify the inode number of the delete file.

The easiest way to know the inode number of a file is

ls -i

Example ls -i

$ ls -i example.txt
6710909 example.txt

The inode number for example.txt is 671909

Another way is to use lsof

Example of lsof

$ ps -ef | grep vi
root     24216 22841  0 10:41 pts/2    00:00:00 vi example.txt

$ lsof -p 24216 
COMMAND   PID USER   FD   TYPE DEVICE     SIZE    NODE NAME
vi      24518 root    4u   REG    8,2    12288 6710944 /tmp/.example.txt.swp

The inode number for /tmp/.example.txt.swp is 6710944

3. Identify the filesystem where the inode is from. 

The easiest way is to use the following command

df -h /your/path

Example

$ df -h /tmp
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda2              57G   20G   34G  37% /

My /tmp is located at /dev/sda2

Using of debugfs to recover the file from inode

1) To use debugfs, you need to first open the file system

debugfs {your_filesystem}

Example

$ debugfs /dev/sda2
debugfs 1.39 (29-May-2006)
debugfs:

2) Use cat command to view the content of the inode

cat < inode_number >

Example
debugfs:  cat <6710909>
hello world
lalal

3. Use dump_inode to dump the inode content to a file

dump_inode  < inode_number > /path/to/file

Example

debugfs:  dump_inode <6710909> /tmp/inode_example.txt

4. Check the content of the inode dump. 

You can use ls and cat command to do this.

Example

$ ls -ali *example*
6710909 -rw-r--r-- 1 root root 18 Dec 16 10:54 example.txt
6710944 -rw-r--r-- 1 root root 18 Dec 16 11:07 inode_example.txt

$ cat inode_example.txt
hello world
lalal
$ cat example.txt
hello world
lalal

As you can see, both files have the identical content. However, you should note that these 2 files have 2 different inode number.

I am still finding a way to restore the dump inode file to the orginal inode number. That is, restore inode_example.txt back to inode number 6710909. If you have some idea, please feel free to tell me.









Comments

Popular Posts