Skip to content

Instantly share code, notes, and snippets.

@djsutherland
Created January 1, 2010 00:33
Show Gist options
  • Save djsutherland/266979 to your computer and use it in GitHub Desktop.
Save djsutherland/266979 to your computer and use it in GitHub Desktop.
A bash script for managing ssh tunnels for smtp (or whatever)
#!/bin/bash
SOCKS_PORT=''
LOCAL_PORT='5525'
SSH_HOST='sccs.swarthmore.edu'
TARGET_HOST='smtp.swarthmore.edu'
TARGET_PORT='25'
while getopts 'D:p:s:h:P:' OPTION
do
case $OPTION in
D) SOCKS_PORT="$OPTARG" ;;
p) LOCAL_PORT="$OPTARG" ;;
s) SSH_HOST="$OPTARG" ;;
h) TARGET_HOST="$OPTARG" ;;
P) TARGET_PORT="$OPTARG" ;;
?) echo "incorrect usage, dummy"; exit -1 ;;
esac
done
shift $(($OPTIND - 1))
if [[ -n "$1" ]]; then
do=$1
else
do='start'
fi
if [[ -n $SOCKS_PORT ]]; then
cmd="ssh -D $SOCKS_PORT -Nf $SSH_HOST"
else
cmd="ssh -L $LOCAL_PORT:$TARGET_HOST:$TARGET_PORT -Nf $SSH_HOST"
fi
function find_pid {
PID=$(ps aux | grep "$cmd" | grep -v 'grep' | awk '{print $2}')
}
function start_tunnel {
find_pid
if [[ -n "$PID" ]]; then
echo "tunnel already running (pid $PID)" 1>&2
exit 1
fi
$cmd
find_pid
echo "started new process: $PID"
}
function stop_tunnel {
find_pid
if [[ -z "$PID" ]]; then
echo "couldn't find a running tunnel" 1>&2
exit 2
fi
oldpid=$PID
kill $PID
find_pid
if [[ -z $PID ]]; then
echo "killed process $oldpid"
else
echo "unable to kill process $PID" 1>&2
exit 3
fi
}
case "$do" in
pid) find_pid;
echo $PID ;;
cmd) echo $cmd ;;
start) start_tunnel ;;
stop) stop_tunnel ;;
restart) (find_pid && stop_tunnel);
start_tunnel ;;
toggle) find_pid;
if [[ -n "$PID" ]]; then stop_tunnel;
else start_tunnel;
fi ;;
*) echo "Incorrect usage: unknown command '$do'";
exit 4 ;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment