AutoDevReverseProxy/script/myssh
2022-11-18 12:21:33 +01:00

113 lines
2.8 KiB
Bash
Executable file

#!/usr/bin/env bash
if [ -z "$SQL_CLI_TEMPLATE" ]
then
if [ $(uname -s) = "Linux" ]
then
SQL_CLI_TEMPLATE='mysql --protocol=TCP -u $MYSQL_USERNAME -p$MYSQL_PASSWORD -h localhost -P 3306'
else
SQL_CLI_TEMPLATE='open \"mysql://$MYSQL_USERNAME:$MYSQL_PASSWORD@localhost:3306\" -a \"Sequel Ace\"'
fi
else
echo -e "Warning, custom client string:\n$SQL_CLI_TEMPLATE"
read -r -p "Continue [Y/n] " CONTINUE
if [[ ! $CONTINUE =~ "^[Yy]" ]]
then
exit
fi
fi
[ -z $SQL_PROXY_HOST ] && SQL_PROXY_HOST="localhost"
[ -z $SQL_PROXY_DB_PORT ] && SQL_PROXY_DB_PORT="3306"
CONNECTION_CACHE="$HOME/.cache/sqlproxy_$SQL_PROXY_HOST"
HELP="Usage: myssh [ls|connect]\n
SUBCOMMANDS:\n
ls: list available database hosts\n
connect: connect to a database host\n
disconnect: Quit existing ssh master session\n
\n
SYNTAX connect host [-u user] [-p password] [-c client]
"
ssh_status() {
ssh -O check -S $HOME/.ssh/controlmasters/%r@%h:%p $SQL_PROXY_HOST > /dev/null 2>&1
echo $?
}
connect() {
mkdir -p $HOME/.ssh/controlmasters
if [ $(ssh_status) -ne 0 ]
then
echo "" > $CONNECTION_CACHE
ssh -o "ControlPersist=10m" -M -S $HOME/.ssh/controlmasters/%r@%h:%p $SQL_PROXY_HOST q
fi
}
disconnect() {
if [ $(ssh_status) -eq 0 ]
then
ssh -O stop -S $HOME/.ssh/controlmasters/%r@%h:%p $SQL_PROXY_HOST q
fi
}
port_forward() {
ACTIVE_HOST=$(cat $CONNECTION_CACHE)
if [ -z $ACTIVE_HOST ] || [ $ACTIVE_HOST != $1:$SQL_PROXY_DB_PORT ]
then
echo "Reconnect"
if [ ! -z $ACTIVE_HOST ]
then
ssh -O cancel -L 3306:$ACTIVE_HOST -S $HOME/.ssh/controlmasters/%r@%h:%p $SQL_PROXY_HOST q
fi
ssh -O forward -L 3306:$1:$SQL_PROXY_DB_PORT -S $HOME/.ssh/controlmasters/%r@%h:%p $SQL_PROXY_HOST
fi
echo $1:$SQL_PROXY_DB_PORT > $CONNECTION_CACHE
}
ls_hosts() {
ssh -S $HOME/.ssh/controlmasters/%r@%h:%p $SQL_PROXY_HOST ls
}
run_client() {
$(eval echo $SQL_CLI_TEMPLATE)
}
MAIN_OPTION=$1
shift
# ensure connection
connect
case $MAIN_OPTION in
ls)
ls_hosts;;
connect)
# check if host is valid
TARGET_HOST=$1
shift
ls_hosts | grep -qe "^$TARGET_HOST$"
GREP_EXIT_CODE=$?
if [ $GREP_EXIT_CODE -eq 0 ]
then
while getopts "u:p:" o
do
case "$o" in
u) MYSQL_USERNAME="$OPTARG" ;;
p) MYSQL_PASSWORD="$OPTARG" ;;
esac
done
port_forward $TARGET_HOST
if [ ! -z $MYSQL_USERNAME ] && [ ! -z $MYSQL_PASSWORD ]
then
run_client
fi
else
echo "Invalid Hostname: $TARGET_HOST."
fi
;;
disconnect)
disconnect;;
*)
echo -e $HELP;;
esac