Results 1 to 10 of 16

Thread: HOWTO: Automatically mount and unmount network shares

Threaded View

  1. #1
    Join Date
    Dec 2006
    Beans
    678

    HOWTO: Automatically mount and unmount network shares

    Here is a script you can run in the background that will automatically detect your network shares as they dynamically come and go from the network, and respond accordingly (i.e., mounting them when the networked connection is available, and unmount it when it disappears). I find this useful for my laptop (which travels) and my desktop (which doesn't, but connects to several other computers that may or may not be on/present at any moment).

    You may an alternative version of this approach more helpful for most applications: http://ubuntuforums.org/showthread.php?t=637258

    First requirement: working network connections. For SAMBA, see either of these links:
    http://doc.gwos.org/index.php/HowToM...resPermanently
    http://www.ubuntuforums.org/showthread.php?t=280473

    NOTE: you must have the connections in your fstab, and you MUST be using "cifs" in place of "smbfs" (I find cifs more reliable anyway - all you need to do is replace instances of "smbfs" with "cifs," they are installed together). Using smbfs will prevent you from being able to unmount. If you happen to be working in a pure *nix environment and can use NFS, this will probably work, but I've not tried it. This script will completely ignore shares not listed in /etc/fstab, meaning it will not interfere with anything else you happen to be doing. Your fstab line must include the "user" option, and should look something like the following:
    Code:
    //IPADDRESS	/media/MOUNT	cifs	auto,user,credentials=/etc/.credentials1,rw,uid=1000,umask=000	0	0
    Also note that if you use a credentials file, as I am here, it must be readable by your account (not just root, as suggested by the above links).
    Note that your fields in fstab must be separated by tabs, not spaces.

    Second requirement: mount.cifs & umount.cifs must be SUID:
    Code:
    sudo chmod +s /sbin/mount.cifs
    sudo chmod +s /sbin/umount.cifs
    Again, if using NFS, there is probably an equivalent requirement, but I've not tested.

    Third requirement: copy this script into a file (e.g., "automount"):
    Code:
    #!/usr/bin/python
    
    '''
    This script assumes that all the network shares in /etc/fstab are accessible
    to the current user.  In addition, the shares need to be CIFS (not SMBFS) in
    order to correctly allow unmounting by the user in the event the share is
    disconnected.  /sbin/mount.cifs & /sbin/umount.cifs must be suid root.
    
    This periodically reads mtab check the status of nework shares,
    and unmounts recently inactive shares.  All inactive shares are then issued a
    ping.  Responsive systems are then mounted.
    
    Only shares listed in fstab are handled; any others shown by mtab are ignored.
    '''
    
    Delay = 120 # number of seconds between checks
    
    import os
    import time
    
    def CheckStatus(Share):
        '''Check mtab to determine if a share is mounted.'''
        Mtab = os.popen('grep \'^//\' /etc/mtab', 'r').readlines() # get mounted shares
        for Line in Mtab:
            if Share in Line: return True
        return False
        
    Shares = {} # dictionary of IP/name : mountpoint
    
    # Read /etc/fstab to identify permanent shares
    fstab = open('/etc/fstab', 'r')
    for EachLine in fstab:
        Line = EachLine.strip()
        if Line[:2] == '//': # then reference to share
            Parts = Line.split('\t')
            Path = Parts[0].split('/')
            Shares[Path[2]] = Parts[1]# 3rd piece is name b/c starts with '//'
    fstab.close()
    
    # Check status of all shares, every Delay seconds
    while True:
        LastTime = time.time() # mark for next time around
        for ShareName, ShareMount in Shares.iteritems():
            if CheckStatus(ShareMount): # this share is mounted, check status
                if os.system('ping -c 1 %s' % (ShareName)) != 0: # ping failed
                    os.system('umount -l %s' % (ShareMount)) # unmount
            else: # share is not mounted, check to see if should mount
                if os.system('ping -c 1 %s' % (ShareName)) == 0: # ping responded
                    os.system('mount %s' % (ShareMount))
        NumSecs = max(0, Delay - (time.time() - LastTime)) # Delay minus elapsed time
        time.sleep(NumSecs) # sleep until next round of pings
    Then:
    Code:
    chmod 755 automount
    sudo cp automount /usr/local/bin
    You can now add "automount" to your programs that start upon login, and your network shares will dynamically appear and disappear.

    It is probably possible to do all this with a shell script, but I'm more comfortable with python for something this sophisticated; feel free to post any simpler alternatives. Also let me know if you encounter problems or get it working with NFS and I'll update accordingly.

    Final note about using cifs vs. smbfs: as per this bug (https://launchpad.net/ubuntu/+source...nit/+bug/42121, with duplicate and more information at https://launchpad.net/ubuntu/+source...it/+bug/49695), you may encounter a delay in shutting down while unmounting fails. I see this on some of my computers, but other than an extra 60 seconds in the shutdown, it's not a problem (and if nothing is mounted, it won't happen). (See post # 7 for the a way around this problem.) Also, you may encounter a problem (again, really just a delay) with mounting during boot, in which case you can just change your fstab entries to "noauto" (the script will mount the shares as soon as you log in anyway).
    Last edited by tweedledee; December 21st, 2007 at 01:34 PM. Reason: Updates

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •