Skip to content

Instantly share code, notes, and snippets.

@dtsmith2001
Created March 27, 2021 13:30
Show Gist options
  • Save dtsmith2001/267fcfe3968e2965739393053fcfe285 to your computer and use it in GitHub Desktop.
Save dtsmith2001/267fcfe3968e2965739393053fcfe285 to your computer and use it in GitHub Desktop.
Keep Reverse Tunnel Open
#!/usr/bin/env bash
#
# MIT License
#
# Copyright (c) 2021 Vallum Sofware, LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Inspired by https://stackoverflow.com/questions/1998297/ssh-check-if-a-tunnel-is-alive
#
# Tested on Ubuntu 18.04 LTS and 20.04 LTS
#
#
# See https://stackoverflow.com/a/45122025/4329358
#
function print_style {
if [ "$2" = "info" ] ; then
COLOR="96m";
elif [ "$2" = "success" ] ; then
COLOR="92m";
elif [ "$2" = "warning" ] ; then
COLOR="93m";
elif [ "$2" = "danger" ] ; then
COLOR="91m";
else #default color
COLOR="0m";
fi
STARTCOLOR="\e[$COLOR";
ENDCOLOR="\e[0m";
printf "${STARTCOLOR}%b${ENDCOLOR}\n" "$1";
}
usage() {
print_style "$0 --hostname <ip-address> --port port_num [-u <username> | --user <username> Supply username (default is ${USER})] [-k private-key | --private-key private-key Supply a private key, otherwise rely in ~/.ssh/config]"
exit 1
}
user_name="${USER}"
private_key=
while [ $# -gt 0 ]
do
case
"-u" | "--user")
shift
user_name="$1"
shift
-k | --private-key)
shift
private_key="-i $1"
shift
--port)
shift
port="$1"
shift
*)
usage
-h | --help
usage
esac
done
if [ ! -v host_name ]
then
print_style "$0: --hostname is required"
usage
elif [ ! -v port ]
print_style "$0: --port is required"
usage
fi
while [ true ]
do
echo "start tunnel"
ssh ${private_key} -N -R ${port}:localhost:22 ${user_name}@${host_name} sleep 10
echo "ssh exits with $?"
sleep 300
echo "restart tunnel"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment