0

I have a host that I need to deploy on a network that I will not have physical access to for some time, so I have set up a persistent reverse ssh connection from a guide, using cron and the script below:

#!/bin/bash

# install with crontab -e
# */1 * * * * /root/scripts/ssh_tunnel.sh > tunnel.log 2>&1

createTunnel() {
  /usr/bin/ssh -i /home/user/cert.pem -N -R 9999:localhost:22 user@example.com
  if [[ $? -eq 0 ]]; then
    echo Tunnel to jumpbox created successfully
  else
    echo An error occurred creating a tunnel to jumpbox. RC was $?
  fi
}

/bin/pidof ssh
if [[ $? -ne 0 ]]; then
  echo Creating new tunnel connection
  createTunnel
fi

The cron job is simply:

crontab -e
*/1 * * * * /root/scripts/ssh_tunnel.sh > tunnel.log 2>&1

I need ssh sessions to re-establish automatically in the event of interruption. Currently if the sshd process on the server is terminated, the process on the client does not terminate, with the result that the script does not try to establish a new session.
I notice that when the connection is started manually from an interactive terminal there is no issue, that is, the client dies along with the server-side process on termination.

Any help would be appreciated, thanks.

  • How do you test it? How do you confirm the connection is terminated? and then re-established or not? I'm testing your setup (Kubuntu client to Debian server in my case) and it works as expected. The only difference is I don't use -i something.pem. When you test it, are you sure there's no other ssh process that prevents your script from re-establishing the connection? /bin/pidof ssh may list process(es) from other users, they can block you. Use flock maybe, example here. – Kamil Maciorowski Aug 17 '17 at 5:06
  • This was tested by adding echo and date statements within the scripts run. In terms of the conection, I was inspecting using netstat on the server and client side but I think that you are right in that connection re-establishment was failing, possibly because a dangling socket on the server. I think autossh may be a better option, with the key being -o ExitOnForwardFailure=yes. – user1330734 Aug 21 '17 at 1:12

Your Answer

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

Browse other questions tagged or ask your own question.