Skip to content

Instantly share code, notes, and snippets.

@Romain-Geissler
Created December 11, 2012 20:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Romain-Geissler/4262040 to your computer and use it in GitHub Desktop.
Save Romain-Geissler/4262040 to your computer and use it in GitHub Desktop.
SSH connection multiplexing in sh (credentials asked only once with several ssh/scp commands).
#!/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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment