views:

638

answers:

4

Hi,

I have written a small bash script which needs an ssh tunnel to draw data from a remote server, so it prompts the user:

echo "Please open an ssh tunnel using 'ssh -L 6000:localhost:5432 example.com'"

I would like to check whether the user had opened this tunnel, and exit with an error message if no tunnel exist. Is there any way to query the ssh tunnel, i.e. check if the local port 6000 is really tunneled to that server?

Thanks,

Adam

+3  A: 

this is really more of a serverfault-type question, but you can use netstat. something like:

netstat -lpnt | grep 6000 | grep ssh

this will tell you if there's an ssh process listening on the specified port. it will also tell you the PID of the process. If you really want to double-check that the ssh process was started with the right options, you can then look up the process by PID in something like ps aux | grep PID

Igor
+5  A: 

This is my test. Hope it is useful.

# $COMMAND is the command used to create the reverse ssh tunnel
COMMAND="ssh -p $SSH_PORT -q -N -R $REMOTE_HOST:$REMOTE_HTTP_PORT:localhost:80 $USER_NAME@$REMOTE_HOST"

# Is the tunnel up? Perform two tests:

# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND

# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
ssh -p $SSH_PORT $USER_NAME@$REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_HTTP_PORT.*LISTEN" \
   > /dev/null 2>&1
if [ $? -ne 0 ] ; then
   pkill -f -x "$COMMAND"
   $COMMAND
fi
Tommy
+1  A: 

Use autossh. It's the tool that's meant for monitoring the ssh connection.

plaes
+1  A: 

Autossh is best option - checking process is not working in all cases (e.g. zombie process, network related problems)

example:

autossh -M 2323 -c arcfour -f -N -L 8088:localhost:80 host2

Vit Bartunek