Reputation: 21
I have a bash script using ssh to remote forward, so that I can login the machine running the script. I use a script because periodically the network needs some sort of auth. If ssh fails, I'll retry. The script is basically this:
while [ 1 ]; do
authentication
ssh -N -v -R 9999:localhost:22 user@$remote_ip
done
The problem is ssh won't exit upon remote forward failure like below:
debug1: Remote: Forwarding listen address "localhost" overridden by server GatewayPorts
debug1: remote forward failure for: listen 9999, connect localhost:22
Warning: remote port forwarding failed for listen port 9999
debug1: All remote forwarding requests processed
The failure is due to this:
debug1: server_input_global_request: tcpip-forward listen localhost port 9999
debug1: Local forwarding listening on 0.0.0.0 port 9999.
bind: Address already in use
channel_setup_fwd_listener: cannot listen to port: 9999
The previous session doesn't end yet, and the port is in use.
Is there a way to check whether ssh succeeds or not? And as a programmer, I really can't understand why it's designed this way. What's the rationale behind this design?
Upvotes: 1
Views: 3653
Reputation: 1120
You can pass in config parameter ExitOnForwardFailure
to tell ssh client to terminate the connection if it cannot set up port forwarding.
ExitOnForwardFailure Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings. The argument must be ''yes'' or ''no''. The default is ''no''.
Something like:
ssh -N -v -R 9999:localhost:22 user@$remote_ip -o ExitOnForwardFailure=yes
Upvotes: 3
Reputation: 3141
Your ssh session has a timeout on the server side, so when you try to reconnect, the previous connection is still listening on port 9000.
Use openvpn, instead of this hacky solution.
Upvotes: -3