How to Undelete files over SSH with Foremost

We’ve all been there. You’re SSH’d into a remote server, trying to delete a folder.

$ pwd


Ok, I’m in the right folder.

$ ls -al to_delete/

total 12
drwxr-xr-x 3 ubuntu ubuntu 4096 2010-11-23 09:09 .
drwxr-xr-x 3 root root 4096 2010-07-15 17:31 ..
drwxr-xr-x 5 ubuntu ubuntu 4096 2010-04-09 15:11 source

Ok, that’s what I want to delete. I’m positive I want this thing gone, I’m going to replace it immediately.

$ rm -rf to_delete


(three seconds later)

SHIT! I needed that!

As you’ve probably now realized, in the future, you should do have done something like this instead
$ mv to_delete to_delete.bak
It’s too late now. What’s done is done, it’s 4 in the morning, and you need those files.

Well luckily for us, you might not be entirely screwed, yet. You need to act fast and deliberately or you may lose data due to other data being written over the data you want to recover.

First we need to find out what partition our data is on.

$ mount

/dev/sda1 on / type ext3 (rw)
proc on /proc type proc (rw)
none on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
udev on /dev type tmpfs (rw,mode=0755)
none on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
none on /dev/shm type tmpfs (rw,nosuid,nodev)
none on /var/run type tmpfs (rw,nosuid,mode=0755)
none on /var/lock type tmpfs (rw,noexec,nosuid,nodev)
none on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
/dev/sda2 on /mnt type ext3 (rw)

So /dev/sda2 is holding /mnt. That’s the ticket. So now $ exit and back to our home computer we can simply say

$ ssh "sudo dd if=/dev/sda2" | dd of=/Users/nickabusey/Downloads/backupfile.iso

Now we have a clone of the partition with the data we care about. All that’s left after that is to recover the deleted data. First install Foremost.

OS X:$ sudo port install foremost

*nix:$ sudo apt-get install foremost

Now, recover the data! In my case I wanted to recover all image files, so I just let it run for all supported file types and got as much as I could out of it.

$ foremost -t all -i backupfile.iso

$ ls output/
audit.txt bmp gif htm jpg png

$ tail output/audit.txt

jpg:= 1307
gif:= 93
bmp:= 1
htm:= 37
png:= 198

Foremost finished at Tue Nov 23 03:23:53 2010


This works pretty well. Many of the images I recovered were corrupted, others didn’t get recovered at all. Another annoying gotcha is that the files are named after their position on the partition rather than their original filenames. So you have to match them back up by hand, and if you have a lot of files this could be extremely tedious if not downright impossible.

At this point I’d like to point out the benefits of regular, redundant backups.

Leave a Reply

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