1

I have 2 servers.

  • Server A is behind a router, to which I have no admin access.
    • It has a user: userA
  • Server B (example.com) is a cloud server with a public ip.
    • It has a user: userB

I am running the following command on Server A, to forward any connections made to Server B on Port 8022 back to Server A on port 22:
ssh -R *:8022:localhost:22 [email protected]

This creates a ssh connection and I have a session open for [email protected]

If I then open another terminal (on another computer) and ssh into [email protected] and once connected run ssh userA@localhost -p 8022 I have an active ssh connection to Server A

This is new to me but all seems to make sense.

I would like to ensure that the inital remote forwarding connection ssh -R is always active. This means if the connection drops I need it to reconnect. If Server A reboots I need it to connect on startup.

How would I go about doing this?

Is there a better approach?

1
  • Thanks @KamilMaciorowski That seemed to do half the trick. I posted an answer below. If you see any room for improvement feel free to answer / comment! Mar 7, 2020 at 4:30

1 Answer 1

0

Based on @Kamil's comment I used autossh.

If I reboot Server B however autossh seemed to exit.

I wrote the following script and have it running every minute on a cron on Server A:

#!/bin/bash
if [ ! -f /proc/$(cat /home/userA/tunnel.pid)/status ]; then
    nohup autossh -M 20000 -R 8022:localhost:22 [email protected] -N > /dev/null 2>&1 &
    echo $! > /home/userA/tunnel.pid
fi

This seems to ensure that the ssh connection is always running (within a minute), regardless of either server closing the connection or rebooting.

If there is a better approach, or I am misunderstanding the full potential of autossh I will accept a better answer

Not the answer you're looking for? Browse other questions tagged .