If you want to connect to some ssh server for port forwarding you use autossh
to keep it alive disregarding network issues.
It you want to switch between several unreliable tcp ports you can use balance
to choose between them.
But when you want to switch between several unreliable ssh servers, you can't direct your ssh client to balance
because different servers will have different hostkeys and using single config entry for them
will ends in either verification errors or in insecure configuration accepting anybody in the middle.
You need to switch host parameter to ssh
but keep other parameters from autossh
intact. Here steps-in this script.
You should define AUTOSSH_PATH=ssh_failover
to force autossh
use this script instead of direct call of ssh
command.
I was too lazy to write complete options parser, so I split options and list of hosts by last non-option argument.
Then --
argument splits list of hosts from remote command passed to ssh
.
Host server1 server1-autossh
HostName server1.example.com
User user1
Host server2 server2-autossh
HostName server2.example.com
User user2
Host server3 server3-autossh
HostName server3.example.com
User user3
Host server1-autossh server2-autossh server3-autossh
LocalForward 1234 remote-hidden-server1:1234
LocalForward 2345 remote-hidden-server2:2345
# AUTOSSH_PATH=ssh_failover.sh autossh -M $((RANDOM%10000+10000)) -T -N server1-autossh server2-autossh server3-autossh