#!/bin/bash # Usage: $0 dbServerHost dbServerPort remoteHost remoteUser # prepare logging LOGFILE=/tmp/`basename $0 .sh`.log function log() { echo $$: $@ >>$LOGFILE } log start $0 at `date` with arguments -"$@"- # find a free port, assign free port to $port function getFreePort() { while true do port=$RANDOM [ $port -lt 1025 ] && continue netstat -an | fgrep -q ':'$port || break done } # the function does the work (see comments inside), arguments: # $1 the remote database host # $2 the remote database port # $3 the remote host for tunnel # $4 the remote user for tunnel function doWork() { # get free local port for the ssh tunnel getFreePort log free port is $port # build tunnel to remote host log start tunnel to $4@$3 and database $1:$2 ssh -l $4 -C -L $port:$1:$2 -N $3 >> $LOGFILE 2>&1 & # wait max up to 20 seconds for the tunnel to start s=1 while ! netstat -an | grep -q ':'$port do log waiting for ssh tunnel -$s- sleep 1 s=$(($s + 1)) if [ $s -gt 20 ] then log unable to start ssh tunnel exit 1 fi done log tunnel built # start I/O copying log start nc copy program for stdin/stdout and localhost:$port nc localhost $port 2>>$LOGFILE # kill background tunnel log killing ssh tunnel kill %1 } # test arguments: $0 dbServerHost dbServerPort remoteHost remoteUser if [ $# -ne 4 ] then log `basename $0` was called with an illegal argument list: "$@" exit 1 fi # do the work doWork $1 $2 $3 $4 log end of $0 at `date` exit 0