dotfiles/bin/ssh-fwd

74 lines
1.5 KiB
Text
Raw Normal View History

2023-06-17 19:04:53 +02:00
#!/bin/bash
2023-04-13 00:04:20 +02:00
step() {
printf '\033[1;32m*\033[0m \033[1m%s...\033[0m\n' "$*"
}
2023-06-17 19:04:53 +02:00
error() {
2023-10-29 17:28:47 +01:00
>&2 printf '\033[1;31mERROR:\033[0m \033[1m%s\033[0m\n' "$error"
return "$1"
2023-06-17 19:04:53 +02:00
}
2023-10-29 17:28:47 +01:00
error_null_arg() {
local error
error="Argument \"${arg_name}\" can't be null"
2023-10-29 17:28:47 +01:00
error 1
2023-04-13 00:04:20 +02:00
}
2023-10-29 17:28:47 +01:00
# Lancer la redirection SSH
start_forwarding() {
ssh \
-f -N \
-L "${local_port}:${target}:${distant_port}" \
"$@" \
"$ssh_host"
}
show_redirection_info() {
lsof -i -P -n | awk '($1 == "ssh" && $10 == "(LISTEN)" && $9 ~ /.*:'"${local_port}"'/) { print }'
}
get_ssh_pid() {
show_redirection_info | awk '{ print $2 }' | sort | uniq
}
2023-10-29 17:28:47 +01:00
# Supprimer la redirection SSH
stop_forwarding() {
start_forwarding -O cancel
if [ "$?" -eq 255 ]; then
echo "Okay then, brutally killing SSH..."
kill "$(get_ssh_pid)"
fi
2023-10-29 17:28:47 +01:00
}
2023-04-13 00:04:20 +02:00
2023-10-29 17:28:47 +01:00
# Retourner 0 si le port de la redirection est déjà utilisé par SSH
is_forwarding_active() {
[ -n "$(show_redirection_info)" ]
}
# Parser les variables
trap error_null_arg EXIT
set -e
arg_name='SSH host' ; ssh_host="$1" ; shift
arg_name='local port' ; local_port="$1" ; shift
arg_name='distant port'; distant_port="$1"; shift
trap - EXIT
unset arg_name
if [ -n "$1" ]
then target="$1"
else target=localhost
fi
set +e
2023-10-29 17:28:47 +01:00
# Branchement principal
if ! is_forwarding_active; then
step "Starting the redirection"
2023-10-29 17:28:47 +01:00
start_forwarding
2023-06-17 19:04:53 +02:00
else
step "Stopping the redirection"
2023-10-29 17:28:47 +01:00
stop_forwarding
2023-06-17 19:04:53 +02:00
fi