Created
October 3, 2011 06:50
-
-
Save wolever/1258581 to your computer and use it in GitHub Desktop.
Bash script to start and background an SSH ControlMaster to speed up SSH in the script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Call `setup_ssh_socket` to setup the control socket (function will return once | |
# the socket is ready to go), and `ssh_target` will connect using the control socket. | |
# Assumes TARGET_HOST variable is set. | |
# The connection is automatically closed when the script exists. | |
# TARGET_HOST="wolever.net" | |
# setup_ssh_control_socket | |
# ssh_target "hostname" | |
debug() { | |
echo "DEBUG: $*" | |
} | |
_atexit_cmds=( ) | |
_atexit_trap_handler() { | |
for cmd in "${_atexit_cmds[@]}"; do | |
eval "$cmd" || true | |
done | |
} | |
trap _atexit_trap_handler EXIT | |
atexit() { | |
_atexit_cmds[${#_atexit_cmds[@]}]="$1" | |
} | |
ssh_target() { | |
ssh -S "$SSH_CONTROL_SOCKET" "$TARGET_HOST" "$@" | |
} | |
setup_ssh_control_socket() { | |
SSH_CONTROL_SOCKET="/tmp/ssh-control-$TARGET_HOST-$$" | |
local ssh_fifo="$SSH_CONTROL_SOCKET-fifo" | |
mkfifo "$ssh_fifo" | |
atexit "rm '$ssh_fifo'" | |
local ssh_cmd="echo ready; while :; do sleep 100; done" | |
ssh -nM -o ControlPath="$SSH_CONTROL_SOCKET" "$TARGET_HOST" "$ssh_cmd" > "$ssh_fifo" & | |
SSH_CONTROL_PID="$!" | |
atexit "kill $SSH_CONTROL_PID 2>/dev/null" EXIT | |
debug "ssh control started at $SSH_CONTROL_PID" | |
debug "waiting for ssh connection..." | |
local ssh_line | |
read -t10 ssh_line < "$ssh_fifo" || { | |
echo "error: ssh connect timeout" | |
return 1 | |
} | |
[[ "$ssh_line" != "ready" ]] && { | |
echo "error: invalid line from SSH: $ssh_line" | |
return 1 | |
} | |
kill -INFO "$SSH_CONTROL_PID" 2> /dev/null || { | |
echo "error: could not establish SSH control channel" | |
return 1 | |
} | |
debug "SSH control channel to $TARGET_HOST started at $SSH_CONTROL_SOCKET" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have an example of using this in a script?