Skip to content
Advertisement

Multi Hop, Self Closing, Background SSH Tunnel

I’m trying to create a multi hop ssh tunnel, that is in the background, and self closing. What I have is…

ssh -L 9999:localhost:9999 user@host1 -t ssh -L 9999:localhost:27017 -N 
-i ./mypem.pem user@host2

This successfully creates a multi hop ssh tunnel that closes the port on host1 after I close the tunnel. However, if I try to fork it to the background, like this…

ssh -f -L 9999:localhost:9999 user@host1 -t ssh -L 9999:localhost:27017 
-N  -i ./mypem.pem user@host2

It runs in the background, but killing the process locally does open the port back on host 1.

Any ideas for a self closing, multi hop, background ssh tunnel? Thanks!

Advertisement

Answer

For self-closing, one can use a simple sleep X command.

$ ssh -f -L 9999:localhost:9999 user@host1 
-t 'ssh -L 9999:localhost:27017 -i ./mypem.pem user@host2 "sleep 3600"'

Note, this doesn’t use the -N option, which is for not running a command, instead, we run a command sleep 3600. This keeps the tunnel up for 1 hour and closes itself after that.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement