Results 1 to 2 of 2
I am needing some help with a script, please. My aim is to write a ksh script or function that will create a tunnel using ssh. I want the local ...
- 04-20-2010 #1Just Joined!
- Join Date
- Apr 2010
- Posts
- 5
script to choose local port from pool for ssh tunneling
I am needing some help with a script, please. My aim is to write a ksh script or function that will create a tunnel using ssh. I want the local port to be automatically selected from a pool of available ports. The same script will be called by multiple users, perhaps concurrently, to tunnel to various remote hosts, so the script should return to the user what local port was chosen from the pool. Here is a basic idea:
I would call this function in this fashion (for example), so I can capture the local port number used, and use that port number in my next command:Code:tunnel() { REMUSER=$1 REMHOST=$2 REMPORT=$3 # loop through the choices of local ports for LOCPORT in 13600 13601 13602 13603 13604 do ssh -o ServerAliveInterval=3 -o PreferredAuthentications=publickey -nfL localhost:$LOCPORT:localhost:$REMPORT -l $REMUSER $REMHOST sleep 10 >/dev/null 2>&1 if [ $? -eq 0 ]; then break fi LOCPORT="all ports in pool exhausted" done echo $LOCPORT }
The basic idea is to break out of the for loop if my ssh tunnel creation is successful. If the local port is being used by another tunnel or program, then the break command won't be run and the next port in the pool will be tried. The problem I'm having is the ssh command always exits with code 0, even if it was not successful in setting up port forwarding. I could redirect the stderr output from the ssh command to a file and grep in it for a "Could not request local forwarding" error message, but that would be pretty hokey. I'm thinking I may have no other good choice. Do you have any ideas?Code:LPORT=`tunnel dave server1 5900` someprogram localhost:$LPORT
The program that uses the tunnel is not compatible with SOCKS, so I need to you plain old -L port forwarding. I do not have the ability to rely on freeware utilities, perl, or other programming languages, so I would really like to stick with plain ksh scripting. The ssh client I am using is Open SSH.
Thanks.
- 04-21-2010 #2Just Joined!
- Join Date
- Apr 2010
- Posts
- 5
Answering my own question. Use the -o ExitOnForwardFailure=yes option on ssh to make it fail to connect and exit with an error code if the tunnel can't be set up. Adding that makes the script above work great!


Reply With Quote