#!/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 # # Name self self=psshd # Extend path to find autossh and start-stop-daemon binaries PATH=/usr/lib/autossh/autossh:/sbin:$PATH # Check we have access to the required binaries cmds=(autossh start-stop-daemon) for cmd in "${cmds[@]}"; do if ! type -p "$cmd" >/dev/null; then printf '%s - Could not find %s in PATH\n' "$self" "$cmd" >&2 exit 127 fi done # Get port in options while getopts ':p:' opt; do case $opt in p) port=$OPTARG ;; \?) printf 'Invalid option %s\n' "$OPTARG" >&2 exit 1 ;; :) printf 'Option -%s requires an argument\n' "$OPTARG" >&2 exit 1 ;; esac done shift $((OPTIND-1)) # If no port, give up with usage instructions if ! [[ $port ]]; then printf 'USAGE: %s -p -- \n' "$self" exit 1 fi # Set up a PID dir rundir=${TMPDIR:-/tmp}/psshd-$UID if ! mkdir -p "$rundir"; then printf 'Could not create directory %s for PID file\n' "$rundir" >&2 exit 1 fi # Export the two settings autossh absolutely needs AUTOSSH_PIDFILE=$rundir/psshd-port-${port}.pid AUTOSSH_PORT=$port export AUTOSSH_PIDFILE AUTOSSH_PORT # Use start-stop-daemon to run it sanely start-stop-daemon \ --start \ --quiet \ --pidfile "$AUTOSSH_PIDFILE" \ --exec "$(type -p autossh)" \ -- "$@"