Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
Adam Matan Avatar asked Jan 04 '10 08:01

Adam Matan


People also ask

How do you check if SSH tunnel is active?

The simplest way to test a ssh tunnel is with the telnet command and with a python http server. For reverse connection, this would be the following. On the local, install python3 and ssh, then. >telnet localhost 8080 Trying 127.0.

How do I keep SSH tunnel alive?

Keeping Tunnel Open-M Specify the port to monitor, 0 disable port monitoring and will restart only on ssh exit. -f is sends autossh to the background before running SSH. ServerAliveInternal is the key here as it will send keep-alive packet every given seconds to avoid SSH session to time-out.


2 Answers

Netcat is your friend:

nc -z localhost 6000 || echo "no tunnel open" 
like image 55
rxw Avatar answered Sep 21 '22 09:09

rxw


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 
like image 39
Tommy Avatar answered Sep 18 '22 09:09

Tommy