Last active
January 18, 2023 23:45
-
-
Save rodneyshupe/8ced3e9ebf4196a4281707b64074cefc to your computer and use it in GitHub Desktop.
Example of opening a ssh tunnel for a web app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Provides an example of how to setup a ssh tunnel on WSL | |
LOCAL_PORT=8080 | |
REMOTE_HOST='localhost' # remote server may be the server being connected to (remote localhost) OR it could be a different server | |
REMOTE_PORT=8080 | |
SSH_ADDRESS='appserver' # this can be user@hostip or an alias configured in ssh config file. | |
if [ "$1" == "-k" ]; then | |
pid=$(netstat -lpnt 2>/dev/null | grep $LOCAL_PORT | grep --only-matching -e ' [0-9]*/docker-prox' | grep --only-matching -e '[0-9]*' | head -1) | |
[ -z $pid ] && pid=$(lsof -i -P 2>/dev/null | grep -e 'ssh.*LISTEN' | awk '{print $2}' | head -1) | |
[ ! -z $pid ] && kill $pid || echo "Unable to determine running instance to kill" | |
exit | |
fi | |
if (nc -z localhost $LOCAL_PORT); then | |
echo -e "Tunnel already exists on port $LOCAL_PORT\nAccess at http://localhost:$LOCAL_PORT\n" | |
else | |
ssh $SSH_ADDRESS -N -f -L $LOCAL_PORT:$REMOTE_HOST:$REMOTE_PORT | |
if ( nc -z localhost $LOCAL_PORT ); then | |
echo -e "\nTunnel Created on Port $LOCAL_PORT\nAccess at http://localhost:$LOCAL_PORT" | |
# open browser | |
#"/mnt/c/Program Files/Google/Chrome/Application/chrome.exe" --profile-directory="Profile 1" 'http://localhost:$LOCAL_PORT' | |
else | |
echo "ERROR: Failed to create tunnel" | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment