Skip to content

Instantly share code, notes, and snippets.

@hydra1983
Last active September 13, 2017 18:32
Show Gist options
  • Save hydra1983/f14b2ee8140429223359a29b21b14c9a to your computer and use it in GitHub Desktop.
Save hydra1983/f14b2ee8140429223359a29b21b14c9a to your computer and use it in GitHub Desktop.
script to start a ssh reverse tunnel using autossh on ubuntu
#! /bin/sh
#
# Author: Edison <hydra1983@gmail.com>
#
# This is a modified version for from Andreas Olsson <andreas@arrakis.se>
# For each tunnel; make a uniquely named copy of this template.
## SETTINGS
#
# remote ssh user
RUSER="sshtunnel"
# remote ssh server
RSERVER=... remote server ip ...
# remote ssh port
RPORT="22"
# remote listening port
RLPORT="10022"
# autossh monitoring port (unique)
MPORT=20000
# the ssh tunnel to setup
TUNNEL="-R ${RSERVER}:${RLPORT}:localhost:${RPORT}"
# You must use the real autossh binary, not a wrapper.
DAEMON=/usr/lib/autossh/autossh
#identity file
IDENTITY_FILE=/etc/autossh/sshtunnel_id_rsa
#
## END SETTINGS
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=`basename $0`
PIDFILE=/var/run/${NAME}.pid
SCRIPTNAME=/etc/init.d/${NAME}
DESC="SSH reverse tunnel"
test -x $DAEMON || exit 0
export AUTOSSH_PORT=${MPORT}
export AUTOSSH_PIDFILE=${PIDFILE}
export AUTOSSH_LOGFILE=/var/log/autossh.log
export AUTOSSH_LOGLEVEL=3
ASOPT=${TUNNEL}" -f -N -i "${IDENTITY_FILE}" -p "${RPORT}" "${RUSER}"@"${RSERVER}
# Function that starts the daemon/service.
d_start() {
start-stop-daemon --start --quiet --pidfile $PIDFILE \
--exec $DAEMON -- $ASOPT
if [ $? -gt 0 ]; then
echo -n " not started (or already running)"
else
sleep 1
start-stop-daemon --stop --quiet --pidfile $PIDFILE \
--test --exec $DAEMON > /dev/null || echo -n " not started"
fi
}
# Function that stops the daemon/service.
d_stop() {
start-stop-daemon --stop --quiet --pidfile $PIDFILE \
--exec $DAEMON \
|| echo -n " not running"
}
case "$1" in
start)
echo -n "Starting $DESC: $NAME"
d_start
echo "."
;;
stop)
echo -n "Stopping $DESC: $NAME"
d_stop
echo "."
;;
restart)
echo -n "Restarting $DESC: $NAME"
d_stop
sleep 1
d_start
echo "."
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
exit 3
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment