Making a .sh script to check if SSH connection exists and if not then connect

Let's assume you are using the following command to establish your SSH connection (I would prefer to use .ssh/config file that will simplify the ssh command, but this is not mandatory):

ssh user@host -fTN -R 2222:127.0.0.1:22 -i $HOME/.ssh/id_rsa
  • the options -fTN will push the connection into the background - I wrote this leading part, because this set of options is critical for my suggestion below;
  • the option -R 2222:127.0.0.1:22 will create the reverse tunnel;
  • the option -i $HOME/.ssh/id_rsa indicates the identity file.

We can use ps -aux | grep "<our command>" | sed '$ d' to check whether the connection is established or not. Based on this our script could be:

#!/bin/bash
SSH_COMMAND="ssh user@host -fTN -R 2222:127.0.0.1:22 -i $HOME/.ssh/id_rsa"

if [[ -z $(ps -aux | grep "$SSH_COMMAND" | sed '$ d') ]]
then exec $SSH_COMMAND
fi

Call this script my_autossh, place it in ~/bin and make it executable. Then run crontab -e and add the following job:

* * * * * $HOME/bin/my_autossh

If you do not want to use Cron, modify the scrip my_autossh in this way:

#!/bin/bash
SSH_COMMAND="ssh user@host -fTN -R 2222:127.0.0.1:22 -i $HOME/.ssh/id_rsa"

while true; do
    if [[ -z $(ps -aux | grep "$SSH_COMMAND" | sed '$ d') ]]
    then eval $SSH_COMMAND
    else sleep 60
    fi
done

And use nohup to push it into the background:

nohup my_autossh >/dev/null 2>&1 &

Read also:

  • How to suspend/resume cronjob if one is already running?