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.

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.


# 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.

4 reaktioner till “Bash script that open and close an ssh-tunnel automagically”

Lämna ett svar

Din e-postadress kommer inte publiceras. Obligatoriska fält är märkta *

Denna webbplats använder Akismet för att minska skräppost. Lär dig hur din kommentardata bearbetas.