-
-
Save bric3/e3c3f61a2abd2781dac0 to your computer and use it in GitHub Desktop.
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