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?
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.
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.
Netcat is your friend:
nc -z localhost 6000 || echo "no tunnel open"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With