Deprecated Behaviour

The inane, sometimes insane, ramblings from the mind of Brenton Alker.

Open and Close SSH Tunnel in Script

I have been using SSH tunnels for a long time. Usually, I just manually open the tunnels I require. But, setting up my new machine (archlinux on a Thinkpad t440s.. shiny!) I’ve been writing a lot of shell scripts to automate much of what I used to do manually.

In that spirit, I wanted a script to create an ssh tunnel and connect my irc client (irssi) to my bouncer (znc), behind my home firewall.

So, this is what I’m using:

ssh -f -o ExitOnForwardFailure=yes -L 6667:localhost:6667 sleep 30

The -f -o ExitOnForwardFailure=yes combination makes ssh wait until the forwarded ports have been established before backgrounding. Effectively, this blocks the script until the ports are ready to use.

The sleep 30 keeps the connection open (in the background) for 30 seconds before ssh terminates. However, if there is an open connection on the tunnel, ssh will wait for it to close before terminating. This means, you have 30 seconds to connect to the forwarded port, then it will stay open as long as you’re using it. So, once I quit irssi, the tunnel closes.

Then, irssi configured to connect to localhost:6667 which is tunneled to localhost:6667 on the target machine, where it finds znc!