Skip to content

Instantly share code, notes, and snippets.

@obriencj
Last active March 21, 2024 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obriencj/4cc5d86bfeb1b621d95415f2a2791b4d to your computer and use it in GitHub Desktop.
Save obriencj/4cc5d86bfeb1b621d95415f2a2791b4d to your computer and use it in GitHub Desktop.
#! /bin/bash
# SSH Control and Proxy wrapper
#
# Expects there to be host configuration alias in ~/.ssh/config that
# matches the name of this script.
#
# Author: Christopher O'Brien <obriencj@gmail.com>
# License: GPLv3
SSH_HOST=$(basename "$0")
SSH_CONTROL="$HOME"/.ssh-control-"$SSH_HOST"
function help() {
cat<<EOF
Controls a re-usable SSH tunnel with SOCKS5 proxy
usage: $(basename ${0}) [CONTROL]
The SOCKS5 proxy will be running on localhost:9999
CONTROL can be one of the following:
start launches the master SSH connection and SOCKS5 proxy. Prints
status if master connection already exists.
stop terminates the master SSH connection.
status shows the status of the master SSH connection.
- launches a new shell using a master SSH connection. Will
start a master connection if one doesn't exist. Any
additional parameters will be passed as shell commands.
help prints this message.
If CONTROL is omitted, acts like - with no additional arguments
EOF
}
function status() {
if [ -S "$SSH_CONTROL" ] ; then
ssh -S "$SSH_CONTROL" "$SSH_HOST" -O check "$@"
else
echo "Not running"
fi
}
function start() {
if [ ! -S "$SSH_CONTROL" ] ; then
ssh -qN -f -MS "$SSH_CONTROL" -D localhost:9999 "$SSH_HOST" "$@" \
|| return 1
fi
status
}
function stop() {
if [ -S "$SSH_CONTROL" ] ; then
ssh -S "$SSH_CONTROL" "$SSH_HOST" -O exit "$@"
else
echo "Not running"
fi
}
function shell() {
if [ ! -S "$SSH_CONTROL" ] ; then
start || return 1
fi
ssh -S "$SSH_CONTROL" -tt $SSH_HOST "$@"
}
function main() {
case "$1" in
"start")
shift
start
;;
"stop")
shift
stop
;;
"status")
shift
status
;;
"-"|"")
shift
shell "$@"
;;
"help"|*)
help
;;
esac
}
main "$@"
# The end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment