Bash script that open and close an ssh-tunnel automagically
My problem was that I needed to connect to a port on a server that only was accessible by ssh. This connection should be made in a bash-script that starts and ends within a limited timeframe. That’s why I needed to solve the problem with a SSH-tunnel. George Notaras has made an article about auto-closing ssh tunnels that describes the problem and a solution that should work for most people. However, I did not need a auto-closing ssh tunnel because I want to close the tunnel whenever I want to.
My solution is a little bit more brute because it kills the tunnel. But hey, it works! Check out the simple solution below.
Prerequisites
For this to work you need to have ssh auto login between the two servers.
I have used this solution successfully with the Nagios monitoring system. Read Nagios check_nt over ssh-tunnel.
#!/bin/bash # Open tunnel and wait for it to open # 12489 = remote portnumber # 3456 = local portnumber # increase sleep-time if slow to connect ssh -f -N -L 3456:localhost:12489 username@somehost & sleep 30 # Run some command that uses the opened tunnel # telnet localhost 3456 # Close the tunnel by killing it sleep 5 CMD="ps -eo pid,args | grep 'ssh -f -N -L 3456:localhost' | grep -v 'grep' | cut -c1-6" #echo $CMD PID=`eval $CMD` #echo $PID kill -9 $PID
You may have to change the parameters to the ps-command for this to work on your nix-machine.

Nagios check_nt over ssh-tunnel | Marcus Nyberg on januari 4th, 2010
[...] not connect the port 12489 that NSClient listens to. The only way to solve the problem was to use a SSH-tunnel that I can open and close whenever I needed [...]