#!/bin/sh set -e; BASE_DIRECTORY="$(cd "$(dirname "$0")"&&pwd)" SSH_SOCKET="${BASE_DIRECTORY}"/%r.%h.%p.ssh_socket SSH_HOST=localhost #Exit ssh master connection when the script exits or is killed. trap "ssh -q -o ControlMaster=no -o ControlPath=${SSH_SOCKET} -O exit ${SSH_HOST};" SIGINT SIGTERM EXIT; #Open a master ssh connection that will be later reused for connection multiplexing. The #ssh client does not execute any command (-N) and goes in background after a connection has been #established (allowing us to wait for the user to enter a password if necessary). #We ensure that this will be killed when the script exits thanks to the previous "trap" #statement. #This allows to run several "ssh" or "scp" commands in the script but opening only one #ssh tunnel, thus speeding up connection times and asking credentials only once. #Make sure the tunnel don't stay endlessly opened thanks to a ControlPersist idle #timer (300 seconds). This prevents lasting connections even if you kill this script #with kill -9, which won't trigger the "trap" statement. ssh -fN -o ControlMaster=auto -o ControlPath="${SSH_SOCKET}" -o ControlPersist=300 "${SSH_HOST}"; ssh -o ControlMaster=no -o ControlPath="${SSH_SOCKET}" "${SSH_HOST}" hostname; ssh -o ControlMaster=no -o ControlPath="${SSH_SOCKET}" "${SSH_HOST}" whoami; ssh -o ControlMaster=no -o ControlPath="${SSH_SOCKET}" "${SSH_HOST}" uptime;