#!/usr/bin/env bash # # Wrapper around autossh and start-stop-daemon for basic persistence. Intended # to be called as a script from profile.d for automatic SSH tunnels. # # Takes one required option -p, the autossh monitoring port number to use. Cut # the options off with -- and the remainder of the arguments are passed to the # autossh binary. # # $ psshd -p 9001 -- -fN -D 8001 remotehost # # @author Tom Ryder # @copyright 2013 # # Path to autossh binary (not any wrapper script) autossh='/usr/lib/autossh/autossh' # Path to start-stop-daemon binary startstopdaemon='/sbin/start-stop-daemon' # Neither of those are likely to be in your PATH if you're a normal user, so we # hardcode the paths and test for their existence if [[ ! -x "$autossh" ]]; then printf "Can't execute ${autossh}!" >&2 exit 1 elif [[ ! -x "$startstopdaemon" ]]; then printf "Can't execute ${startstopdaemon}!" >&2 exit 1 fi # Get port in options while getopts ':p:' opt do case "$opt" in p) port="$OPTARG" ;; \?) printf "Invalid option $OPTARG" >&2 exit 1 ;; :) printf "Option -$OPTARG requires an argument" >&2 exit 1 ;; esac done shift "$((OPTIND-1))" # If no port, give up with usage instructions if [[ ! -n "$port" ]] then printf "USAGE: $0 -p -- " exit 1 fi # Set up a PID dir dir="${TMPDIR:-/tmp}/psshd-${UID}" if ! mkdir -p "$dir"; then printf "Couldn't create directory ${dir} for PID file" >&2 exit 1 fi # Export the two settings autossh absolutely needs AUTOSSH_PIDFILE="${dir}/psshd-port-${port}.pid" AUTOSSH_PORT="$port" export AUTOSSH_PIDFILE AUTOSSH_PORT # Use start-stop-daemon to run it sanely "$startstopdaemon" \ --start \ --quiet \ --pidfile "$AUTOSSH_PIDFILE" \ --exec "$autossh" \ -- "$@"