3

Good day, I have the shell script which does a lot of things including opening SSH tunnels to the specific servers and services. No problem with setting tunnel up, test it and shut tunnel down. But I have an issue with keeping tunnels alive. Unfortunately I can't change configuration on the server, so I need to implement some kind of "keep alive mechanism" on my side. Here is the function which opens the tunnel:

ssh_tunnel_up () {
  if lsof -Pi :${local_port} -sTCP:LISTEN -t > /dev/null ; then
  echo "Port is in use, please check with netstat -anlp | grep   ${local_port}. Exiting..."
else
/usr/bin/ssh -24 -fN ${username}@${node_dev} -L ${server_local_port}:${server_dev}:${server_remote_port}
   if [[ $? -eq 0 ]]; then
    echo "Tunnel to Server UI created successfully"
   else
    echo "An error occurred creating a tunnel  RC was $?"
   fi
 fi

}

Here is the function which terminates the tunnel:

ssh_tunnel_down () {
   if lsof -Pi :${local_port} -sTCP:LISTEN -t >/dev/null ; then
     while lsof -t -i:${local_port} > /dev/null ; do
       echo "Port is in use. Closing the port"
       kill -9 $( lsof -t -i:${local_port} )
       sleep 1
     done
   else
     echo "Port is already free. Nothing to do. Exiting..."
   fi
}

My question is, how to keep the tunnel alive and how to terminate the "keep alive mechanism" when you terminate the tunnel. I guess I have to use while do done loop, but I can't figure out how to implement this.

Thank you very much, Alex

1

In (HOMEDIR)/.ssh/config, add this:

Host *
ServerAliveInterval 60
1
  • Glad to help, Happy new year to you – Orphans Dec 30 '16 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.