sshtunnelingssh-tunnel

ssh: check if a tunnel is alive


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?


Solution

  • 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