Pages

Monday, July 16, 2012

Automounting Network partitions

If you have network drives that you would like to be auto-mounted on startup on your Linux box, then the obvious way to do this seems to be to put the appropriate line in /etc/fstab. (Note that for Windows shares, the appropriate packages have to be installed - samba and smbfs).

However, if the fstab is executed before the network comes up, you have a problem - the mount will fail. The workaround is to either
  1. not do auto-mount, OR
  2. delay the mount till the network is up OR
  3. to use a program written specifically for this situation - Autofs. 

Despite a lot of struggling, autofs did not work, so went to option #2. The scheme is simple, after the system boots I run a small script to check if the network is up (by pinging a known server). I keep trying at fixed intervals till the network is found to be up, then I mount the remote drives. Note that corresponding entries have been made in /etc/fstab.

1. Create entries in fstab:

The fstab entries look like this:
#Bhaskara
//server/folder /mount-pointhome cifs defaults,noauto,locale=en_IN,uid=networkusername,password=networkpasswd,gid=localgroup,user=localuser 0 0

The "noauto" option ensures that these will not get mounted along with the local drives at bootup.

2. Create the script

Now to create a script which, when called, will check if the network is up, and if it is, will mount the drive. This script is saved as (in this example):
/home/myuser/bin/mount_drives 
Ensure that you make this file executable.
#!/bin/bash
MAX_TRIES=60; # Defines the number of times to atempt
DELAY=5;      #Delay between successive attempt

#A Variable to keep track of network status:
# 0: Working
# non-zero: not working
NETSTAT=1;

#Number of tries made:
COUNT=0;

#Keep trying to reach the network:
while [ $NETSTAT != 0 ]; do
ping -A -c 5 server

#Get return value for ping
NETSTAT=$?

#Increment count value

COUNT=$[$COUNT+1]

        #If max no. of tries exceeded then quit
        if [ $COUNT = $MAX_TRIES ]; then
        exit 1
        fi

       
if [ $NETSTAT != 0 ]; then
        sleep $DELAY
        fi
done

sudo mount //server/folder
This script will attempt to reach the server (by ping) every DELAY seconds, and will try a maximum of MAX_TRIES number of times.
Now the only thing left to do is to:

3. Run this script at every bootup.

To do this, simply add a line to the end of /etc/init.d/rc.local:

/bin/bash /home/myuser/bin/mount_drives




No comments: