Skip to content

Instantly share code, notes, and snippets.

@mutsune
Last active August 10, 2020 02:07
Show Gist options
  • Save mutsune/7986538 to your computer and use it in GitHub Desktop.
Save mutsune/7986538 to your computer and use it in GitHub Desktop.
.ssh/config から LocalForward と DynamicForward の記述部分を読み取って、autossh でトンネルを掘ってもらうスクリプトです。
#!/bin/bash -e
SSH_CONFIG=~/.ssh/config
# ポートは適当
MONITOR_PORT=58626
_monitor_port_inc() { MONITOR_PORT="$(expr ${MONITOR_PORT} + 1)"; }
_is_local_forward() { [ $(echo "${1}" | egrep "^(\d)+:(\d|\.)+:(\d)+$") ]; }
_is_dynamic_forward() { [ $(echo "${1}" | egrep "^(\d)+$") ]; }
_autossh_local() { _autossh L "${1}" "${2}"; }
_autossh_dynamic() { _autossh D "${1}" "${2}"; }
_autossh() { autossh -M "${MONITOR_PORT}" -f -N -t "-${1}" "${2}" "${3}"; _monitor_port_inc; }
FORWARDING_HOSTS=\
$(awk '
$1 == "Host" {
host = $2;
next;
}
$1 == "LocalForward" {
$1 = "";
sub( /^[[:space:]]*/, "" );
target = $1":"$2;
}
$1 == "DynamicForward" {
$1 = "";
sub( /^[[:space:]]*/, "" );
target = $1;
}
target != "" {
printf "%s,%s\n", host, target;
target = "";
}
' "${SSH_CONFIG}")
# tunneling by autossh
for FOREARDING_HOST in ${FORWARDING_HOSTS}; do
DST_HOSTNAME="$(echo "${FOREARDING_HOST}" | cut -d "," -f 1)"
FORWARDING_ARG="$(echo "${FOREARDING_HOST}" | cut -d "," -f 2)"
if _is_local_forward "${FORWARDING_ARG}"; then
_autossh_local "${FORWARDING_ARG}" "${DST_HOSTNAME}"
fi
if _is_dynamic_forward "${FORWARDING_ARG}"; then
_autossh_dynamic "${FORWARDING_ARG}" "${DST_HOSTNAME}"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment