How To: Recover Deleted Files in Linux Using Photorec

Frequently I get messages like “I have accidentally deleted my project. Is there any way to recover it in Linux?” or “I worked really hard on that program and managed to deleted it right before submission πŸ™ How do I recover?”. Well I didn’t really have any idea on “How to actually recover deleted files in Linux”.

A few days back I was designing the new logo for Videocache in Inkscape. After finishing the design, I saved the svg file carefully. And deleted other images which I embedded in the logo. A few moments later I realized that I just screwed up myself by deleting all those files as the svg file is now good for nothing.

I searched a lot on recovering files in Linux but in vain. Then a friend (bitgeek) told me about Photorec. I managed to recover all the files using photorec. I thought it would be a good idea to let others know and spread a good word about Photorec. Below is a step by step howto on using Photorec to recover your files.

What is Photorec?

From Photorec website,

PhotoRec is file data recovery software designed to recover lost files including video, documents and archives from Hard Disks and CDRom and lost pictures (thus, its ‘Photo Recovery’ name) from digital camera memory. PhotoRec ignores the filesystem and goes after the underlying data, so it will still work even if your media’s filesystem has been severely damaged or re-formatted.

For This HowTo

Lets say I had a file download_arrow.png in /home/saini/Desktop which I have removed accidentally. Login as root and create a directory recover which will be used to store all the recovered files.

Install testdisk/PhotoRec

Photorec comes as a part of testdisk package in Fedora (I hope its same for other distributions as well). Use yum to install testdisk.

[root@fedora-tips ~]$ yum install testdisk

Launch Photorec

Once you are done with installation. Open a terminal and launch photorec (as root).

[root@fedora-tips recover]$ photorec

Select Hard Disk

If you have more than one hard disk in your system, select the one from which you have deleted the file(s).

PhotoRec Hard Disk Selection

Select Partition Type

If your hard disk has Linux partitions, then select [Intel].

PhotoRec Partition Selection

Select Filetype Option

Move to [File Opt] and press enter. Here you can disable all file types by pressing ‘s’ . Use space to toggle the check button. Now since we removed a png file, we are going to check only png file type.

PhotoRec Filetype Selection

Select Options

Photorec also has a list of different options. Under normal circumstances you don’t need to modify them

PhotoRec Option Selection

Select Partition

Move the selector to the partition from which you have removed the file. Then press enter on search.

PhotoRec Partition Selection

Select Filesystem Type

If you are using Linux, its going to be ext2/ext3/ext4. So the default selection is file.

PhotoRec Partition Selection

Select Space for Analysis

Select free if you didn’t write to that partition after removing the particular file otherwise select whole.

PhotoRec Space Selection

Select a Directory to Recover Files

Now select the path where the recovered files will be stored. Then press ‘Y’.

PhotoRec Recovery Directory Selection

Recovery Progress

Photorec will show how many files it has recovered.

PhotoRec Recovery Progress

All recovered file will be stored in the directory selected above. Open them in a file browser and you’ll get the removed file there. I hope this howto will help you recovering files you accidentally delete πŸ™‚

 

TIP: Simple Regular Expression for Email Validation

I was playing around with Ruby on Rails and needed an email field for some application. I thought of validating the email address before actually saving it. Googled for same and got tons of results, but none of them was perfect. Few were somewhat exhaustive but horribly difficult to understand and those which were simple wereΒ  not exhaustive enough for practical use. I thought I’ll just write the regex myself and came up with the following. I have tested it for few weird cases like an email hosted on a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.exmaple.com (a subdomain deep down the hierarchy) etc.

^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$

I hope it’ll be of help. And don’t forget to pen down your suggestions via comments.

 

How To: Install and Configure GitWeb

UPDATE : I recommend using GitList instead of GitWeb. GitList is much easier to setup and has a better web interface. Continue reading this post if you looking for GitWeb setup instructions specifically.

Goal

Setting up gitweb (web interface for SCM software git) for your project’s git repository for public access and developer commits via ssh.

Assumptions

  1. You already have your project’s git repository.
  2. You have hosting space somewhere to host gitweb.
  3. You have root access.
  4. You are using Apache as webserver.

Example for this howto

Project : VideoCache
Domain for gitweb : git.cachevideos.com
URL for git access for videocache : http://git.cachevideos.com/videocache.git
Actual path on server : /home/saini/domains/cachevideos.com/git
Git repository : /home/saini/projects/videocache/

Installation

Installation is pretty easy. Just one single command would do everything.

[root@localhost ~]# yum install gitweb (do as root)

This will create a directory /var/www/git which is default for gitweb.

Copy the directory /var/www/git/ to /home/saini/domains/cachevideos.com/git

[root@localhost ~]# cp -r /var/www/git /home/saini/domains/cachevideos.com/git

Configuration

1. GitWeb

Open the file /etc/gitweb.conf (it may or may not be there) and add the following lines to it.

# Change This
$projectroot = '/home/saini/domains/cachevideos.com/git';
# Change This
$site_name = "Kulbir Saini's git trees.";
# Don't Change the variables below
$my_uri = "/";
$home_link = '/';
@stylesheets = ("/gitweb.css");
$favicon = "/git-favicon.png";
$logo = "/git-logo.png";

2. Apache

Open the file /etc/httpd/conf.d/git.conf and clear all the lines that are already there and add the following lines to it

  DocumentRoot /home/saini/domains/cachevideos.com/git
  ServerName git.cachevideos.com
  ErrorLog "/home/saini/domains/cachevideos.com/logs/error_log"
  CustomLog "/home/saini/domains/cachevideos.com/logs/access_log" combined
  SetEnv  GITWEB_CONFIG  /etc/gitweb.conf
  DirectoryIndex gitweb.cgi
 
    Allow from all
    AllowOverride all
    Order allow,deny
    Options +ExecCGI
    AddHandler cgi-script .cgi
 
      SetHandler cgi-script
 
    RewriteEngine on
    RewriteRule ^[a-zA-Z0-9_\-]+\.git/?(\?.*)?$ /gitweb.cgi%{REQUEST_URI} [L,PT]

3. Git repository configuration

Go to your git repository (/home/saini/projects/videocache/) and make the following changes.

(a). Open file .git/description and add a short nice description for your project.

videocache is a squid url rewriter plugin written in Python to facilitate youtube, metacafe, dailymotion, google, vimeo, msn soapbox, tvuol.uol.com.br, blip.tv, break.com videos and wrzuta.pl audio caching.

(b). Open file .git/config and append the following lines

[gitweb]
  owner = "Kulbir Saini"

Copy project’s git repository for gitweb

Copy the /home/saini/projects/videocache/.git directory to /home/saini/domains/cachevideos.com/git/videocache.git

[root@localhost ~]# cp -r /home/saini/projects/videocache/.git /home/saini/domains/cachevideos.com/git/videocache.git

Finishing Step

Restart Apache webserver.

[root@localhost ~]# service httpd restart

Now you can browser a list of your projects’ git repositories at http://git.cachevideos.com/ .

Adding another project repository

Just copy the project repository’s .git directory to /home/saini/domains/cachevideos.com/git/prjoect_name.git. And it’ll be shown on the list.

Committing (pushing) to the repository

For committing to the repository via ssh use the following command.

# Pushing everything (Please see the username)
[root@localhost videocache]# git push --all ssh://saini@git.cachevideos.com/~saini/domains/cachevideos.com/git/videocache.git

To update tags on the remote repository use this command.

# Pushing all tags
[root@localhost videocache]# git push --tags ssh://saini@git.cachevideos.com/~saini/domains/cachevideos.com/git/videocache.git

Well, if you consider just the web interface and committing part for your project, thats all. But things can be fine tuned further. Below are few hacks!

1. Enabling nice urls.

By default the urls for browsing repository via git web are pretty crappy and difficult to remember. The RewriteRule and RewriteEngine lines in your Apache configuration file (/etc/httpd/conf.d/git.conf) takes care of that and produce nice and clean urls.

So you can browser the repository via http://git.cachevideos.com/videocache.git instead of http://git.cachevideos.com/?p=videocache.git;a=summary.

2. Enabling remote ls (git-ls-remote or git ls-remote)

This is the most trickiest part. If you try the command below, it won’t produce any output

[root@localhost ~]# git-ls-remote http://git.cachevideos.com/videocache.git

You need to go to project’s repository in gitweb and then run the following command to update the server info for git.

[root@localhost ~]# cd /home/saini/domains/cachevideos.com/git/videocache.git/
[root@localhost ~]# git-update-server-info

Try the ls-remote command now and it should succeed by producing all the branches and tags in the remote repository.

But there is a problem, you have to run the above command after every commit to the remote repository. To solve this issue, you can enable post-update hook for the project’s repository in gitweb. Use the following command to enable it.

[root@localhost ~]# cd /home/saini/domains/cachevideos.com/git/videocache.git/
[root@localhost ~]# chmod +x post-update

The above command will update the server info automatically every time you commit.

Thats all you need to do for setting up gitweb. I hope this will be helpful.

 

How To: Boot Fedora Faster

Note: These tricks apply to any Linux based OS. But I have tested them only on Fedora, so can’t say whether they’ll work on other Linux(s).

My current Fedora installation is now almost one and a half years old. Yes. I am still using Fedora 7 πŸ˜€ I have Fedora 10 on my other machine. Coming to the agenda, my Fedora installation has grown beyond control and I have services from named, squid, drbl, privoxy, vsftpd, vbox*, smb and what not on a personal desktop. These services really force my system startup to slow down to more than two minutes. While shutting down, its very easy to just cut the power supply but while booting up I can’t help and it frustrates me. And what frustrates me further that I have 4GB DDR2 RAM and AMD64 X2 5600+ (2.8GHz x 2) and booting time is still more than two minutes.

Agenda

  • Boot Fedora faster using whatever techniques possible.

Remove the services from normal order and delay their execution to a later stage. So, services like network, squid, privoxy, named, vsftpd, smb etc. doesn’t make sense unless I am not logged in and using them. Let us start them after we have login screen.

Turn off all the services by using the command

[root@bordeaux ~]# chkconfig service_name off

where service_name is the service you want to turn off.

Now create a file /etc/startup.sh. Enter a line like this

[root@bordeaux ~]# service service_name start

for every service that you have turned off in the Step 1.1 and you want it to be running after your machine starts up. Now, your startup.sh file should look like this

service network start &
service sshd start &
modprobe it87 &
modprobe k8temp &
/usr/bin/iptraf -s eth0 -B &
/usr/bin/iptraf -s lo -B &
service squid start &
service privoxy start &
service httpd start &
service mysqld start &
service named start &
service smb start &
service vboxdrv start &
service vboxnet start &
service vsftpd start &

Add the following line to /etc/rc.local file

/bin/bash /etc/startup.sh &

Done!!! Notice the &s in both files. They are for execution in background so that a process can block boot process. You’ll observe a drop of 10-20 seconds in system startup time.

Problem with Hack #1 : The execution is not really parallel. It executes like a process in the background. So we can’t get the real advantage of parallel execution.

Hack #2 solves this problem. Now we don’t put processes in background. We use daemon forking to fork a separate daemon process which will start all the services for us in parallel. Here we’ll get the real advantage and startup time will decrease further.

This step is totally similar to Step 1.1. So skipping it.

This step is also similar to Step 1.2. The /etc/startup.sh file should look like this.

service network start
service xinetd start
service crond start
service anacron start
service atd start
service sshd start
service rpcbind start
service rpcgssd start
service rpcimapd start
modprobe it87
modprobe k8temp
/usr/bin/iptraf -s eth0 -B
/usr/bin/iptraf -s lo -B
service nasd start
service squid start
service privoxy start
service httpd start
service iptables start
service lm_sensors start
service mysqld start
service named start
service nfs start
service nfslock start
service smb start
service vboxdrv start
service vboxnet start
service vsftpd start
service autofs start
service smartd start

Notice the absence of &s in the file.

Download the attached startup.py file attached at the end of this post or copy paste the following code to /etc/startup.py file.

#!/usr/bin/env python
# (C) Copyright 2008 Kulbir Saini
# License : GPL
import os
import sys
def fork_daemon(f):
    """This function forks a daemon."""
    # Perform double fork
    r = ''
    if os.fork(): # Parent
        # Wait for the child so that it doesn't defunct
        os.wait()
        # Return a function
        return  lambda *x, **kw: r
    # Otherwise, we are the child
    # Perform second fork
    os.setsid()
    os.umask(077)
    os.chdir('/')
    if os.fork():
        os._exit(0)
    def wrapper(*args, **kwargs):
        """Wrapper function to be returned from generator.
        Executes the function bound to the generator and then
        exits the process"""
        f(*args, **kwargs)
        os._exit(0)
    return wrapper
 
def start_services(startup_file):
    command = '/bin/bash ' + startup_file + ' > /dev/null 2> /dev/null '
    os.system(command)
    return
 
if __name__ == '__main__':
    forkd = fork_daemon(start_services)
    forkd(sys.argv[1])
    print 'Executing ', sys.argv[1], '[  OK  ]'

Add the following line to your /etc/rc.local file.

/usr/bin/python /etc/startup.py /etc/startup.sh

Thats it. Done!!! Now you’ll experience a boost of about 25-30 seconds of decrease in boot time.

Stats of my machine

With all services started in normal order : 2minutes.
With Hack #1 : 1minute 42 seconds.
With Hack #2 : 1minute.

Warning : These hacks may break your system and can make it unusable. Use at your own risk.

 

How To: Install Fedora without CD or DVD

Note: If you are new to Fedora/Linux, I highly recommend the book “Fedora Linux Toolbox

[amazon-product alink=”0000FF” bordercolor=”000000″ height=”240″]0470082917[/amazon-product]

Use Case

  1. When you don’t have CD / DVD drive on your system.
  2. You have Fedora DVD but your system has only a CD Drive.
  3. You don’t want to waste time and resources in burning iso on optical media.

Pre-requisites

  1. You have a Fedora DVD iso or rescue cd iso.
  2. You have a Linux installation on your system.
  3. You have a partition (FAT32, ext2, ext3) which you will not format while installing the new OS.

How to proceed

Let us assume you want to install Fedora 9 on your system and you have a Linux distro already installed on your system. You have downloaded the Fedora DVD iso (Fedora-9-DVD-i686.iso). And you have a FAT32/ext2/ext3 partition /stuff/ which you will not format during installation.

Step 1 : Move the Fedora DVD iso to /stuff/ directory.

[root@saini saini]# mv Fedora-9-DVD-i686.iso /stuff/ [Enter]

Step 2 : Mount Fedora DVD iso on /mnt/

[root@saini saini]# mount /stuff/Fedora-9-DVD-i686.iso /mnt/ -ro loop [Enter] (do as root)

Step 3 : Copy the initrd.img and vmlinuz to /boot/ partition

[root@saini saini]# cd /mnt/isolinux/ [Enter]
[root@saini isolinux]# cp initrd.img vmlinuz /boot/ [Enter] (do as root)

Step 4 : Create grub entry for booting into Fedora 9

Add these lines at the end of your /boot/grub/grub.conf file.

title Fedora 9 (New installation)
    kernel /vmlinuz
    initrd /initrd.img

Step 5 : Note the device having Fedora DVD iso

[root@saini saini]# df -h [Enter]
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda3              15G  9.5G  4.1G  70% /
/dev/sda8             135G  116G   13G  91% /stuff
/dev/sda5             4.8G  1.2G  3.4G  26% /home
/dev/sda1              99M   12M   82M  13% /boot

In this case /dev/sda8 contains Fedora DVD iso. Note this down as you need it later.

Step 6 : Reboot

Reboot your system and boot into the Fedora 9 (New installation) grub entry.

Step 7 : Install from hard disk

While in installation wizard, select “Hard drive” as installation method and choose /dev/sda8 as it contains the Fedora DVD iso. And rest is damn easy.