2013-11-20

Bash script to manage sshfs


If you wanna use sshfs, this software should be installed:


$apt-get install openssh-client openssh-server sshfs 

If server not always online and you want to mount automatically sshfs when server online, I use this bash.

Bud before running bash, you have to be able connect to server without a password.

You have to create pabulic key on client

$ssh-keygen -t rsa

And then copy key from client ~/.id_rsa.pub (single long line in the text file)
to server ~/.ssh/authorized_keys 

I added this script to "Startup Applications".


Download sshfs.bash

#!/bin/bash

echo $0

# =======================================================
# CONFIGURATION
REMOTE_IP="192.168.1.2"
REMOTE_USER="user"
REMOTE_PATH="/home/"
MOUNT_POINT="/media/sshfs/"

# =======================================================
# VARIABLES
BOOL_ONLINE=0
BOOL_MOUNTED=0
BOOL_PID_RUN=0
# =======================================================
# FUNCTIONS


FUNC_remote_net_stat()
{
NET_STATUS=`ping ${REMOTE_IP} -c 1`

    if grep -q "64 bytes from ${REMOTE_IP}: icmp_req=1 ttl=64 time=" <<< "$NET_STATUS" ; then
        echo "ONLINE"
        BOOL_ONLINE=1
        else
        echo "OFFLINE"
        BOOL_ONLINE=0
    fi
}


FUNC_pid_status()
{
PID_STAT=`ps axu`

    if grep -q "sshfs ${REMOTE_USER}@${REMOTE_IP}:${REMOTE_PATH}" <<< "$PID_STAT" ; then
        BOOL_PID_RUN=1
        echo "PID RUNNING"
        else
        BOOL_PID_RUN=0
        echo "PID DEAD"
    fi
}

# =======================================================
# SCIPT BODY


    while true
    do
        FUNC_remote_net_stat
        FUNC_pid_status
       
        if [ $BOOL_ONLINE -eq "1" ]; then
       
       
            if [ $BOOL_PID_RUN -eq "1" ]; then
            BOOL_MOUNTED=1
            fi
       
            if [ $BOOL_MOUNTED -eq "0" ]; then
            echo "MOUNTIN SSHFS ..."
   
            SSH_MOUNT=`sshfs ${REMOTE_USER}@${REMOTE_IP}:${REMOTE_PATH} ${MOUNT_POINT}`

                if [ ! -z "$SSH_MOUNT" ]; then
                echo "ERROR ${SSH_MOUNT}"
                else
                BOOL_MOUNTED=1
                fi
            echo "DONE"    
            fi   
        fi
       
       
        if [ $BOOL_ONLINE -eq "0" ]; then
       
            if [ $BOOL_MOUNTED -eq "1" ]; then
            echo "KILLING SSHFS ..."
            kill `pidof ssh`
            BOOL_MOUNTED=0
            echo "DONE"
            fi
        fi
       
        if [ $BOOL_MOUNTED -eq "1" ]; then
       
            if [ $BOOL_PID_RUN -eq "0" ]; then
            BOOL_MOUNTED=0
            fi
        fi       
       
    sleep 5
   
   
    done


echo "EXIT"

# THE END
# =======================================================

No comments:

Post a Comment