Using lsof to Recover Deleted Files

If an open file is deleted accidentally, it is possible to use lsof to recreate a copy of the file; provided this is done before the file is closed by the application holding it open.

If you have inadvertently removed a file from the filesystem it is still recoverable if the application using the file it still running. This is because the inode is still open and therefore the data blocks are still on the disk until the application closes the file or exits.

Through the use of lsof and /proc the file system entry for the file can be recreated.

The easiest way to explain this is by way of an example.

  • Make a file:
/> cd /tmp 
tmp> ls -lR 
tmp> > /tmp/myfile  
tmp> ls -l myfile    
-rw-r--r--  1 fred ftp 11567585 Nov 23 08:44 myfile  
tmp> stat myfile  
File: `myfile'Size: 11567585
Blocks: 22640
IO Block: 4096   regular file
Device: 900h/2304d Inode: 48871 Links: 1 
Access: (0644/-rw-r--r--)
Uid: ( 1900/fred) Gid: (50/ftp) 
Access: 2006-11-23 08:44:32.000000000 +0000 
Modify: 2006-11-23 08:44:26.000000000 +0000  
Change: 2006-11-23 08:44:26.000000000 +000
  • Run something to hold the file open:
tmp> less myfile & 
[1] + Suspended (tty output) less myfile
  • “Accidentally” remove the file:
tmp> rm myfile 
tmp> ls -l myfile
ls: myfile: No such file or directory
  • Use lsof to show the open file descriptor of the process:
tmp> lsof | grep myfile 
less 11230 fred 4r REG 9,0 115675854 8871 /tmp/myfile (deleted)

The second column is the PID of the process that has this file open and the fourth field the file descriptor that the process is using to access the file.

  • Locate the open file descriptor in /proc:
tmp> ls -l /proc/11230/fd/4 
lr-x------ 1 fred ftp 64 Nov 23 08:49 /proc/11230/fd/4 -> /tmp/myfile (deleted)
  • The open file can now be copied back to its original location:
tmp> cp /proc/11230/fd/4 myfile 
tmp> ls -l myfile
-rw-r--r-- 1 fred ftp 11567585 Nov 23 08:54 myfile
tmp> stat myfile
File: `myfile'Size: 11567585
Blocks: 22640
IO Block: 4096 regular file Device: 900h/2304d
Inode: 48878 Links: 1
Access: (0644/-rw-r--r--)
Uid: ( 1900/fred) Gid: (50/ftp)
Access: 2006-11-23 08:54:28.000000000 +0000
Modify: 2006-11-23 08:54:28.000000000 +0000
Change: 2006-11-23 08:54:28.000000000 +0000

**NOTE: Note the new file has a different inode than the original as it is a copy NOT the original one opened by the process. This may be important as any changes made by the application to the original after this copy has been made will not be recovered.

————————-

  • masterkenneth

One thought on “Using lsof to Recover Deleted Files”

  1. thanks for that , is was very helpfull
    note if the process is locking several files they can be at other address , not necessarily 4

Leave a Reply

Your email address will not be published. Required fields are marked *