I believe that this will work (worked in my experiments, albeit, I could only interrupt the connection manually, so not sure if I replicated exactly your broken pipe scenario):
ssh -o ExitOnForwardFailure=true -R 9000:localhost:9000 -Nf remote-server
The main trick is that you are creating a "standalone" ssh connection only for the purpose of port forwarding and putting it into the background (-Nf
options). This way, when the connection terminates (broken pipe, e.g.), it should free the port.
The ExitOnForwardFailure
option is only there so that the next time you try to make a connection, you will see on STDOUT the fact that the port is still open on the server. If you still need to do something more complicated to manually kill the connection on the server, you could use the exit code from a failed ssh
with the ExitOnForwardFailure
option to do something more complicated.