dotfiles/bin/ssh-fwd

59 lines
1 KiB
Text
Raw Normal View History

2023-06-17 19:04:53 +02:00
#!/bin/bash
2023-04-13 00:04:20 +02:00
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="Variable \"${1}\" can't be null"
error 1
2023-04-13 00:04:20 +02:00
}
2023-10-29 17:28:47 +01:00
parse_variable() {
! :
2023-04-13 00:04:20 +02:00
}
2023-10-29 17:28:47 +01:00
# Parser les variables
trap error_null_arg EXIT
set -e
ssh_host="$1"
shift
parse_variable ssh_host "$1" 'SSH host'
parse_variable local_port 'local port'
parse_variable distant_port 'distant port'
trap - EXIT
set +e
# Lancer la redirection SSH
start_forwarding() {
ssh \
-f -N \
-L "${local_port}:${target}:${distant_port}" \
"$@" \
"$ssh_host"
}
2023-10-29 17:28:47 +01:00
# Supprimer la redirection SSH
stop_forwarding() {
start_forwarding -O cancel
}
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() {
lsof -i -P -n \
| awk '($1 == "ssh" && $10 == "(LISTEN)") { print $9 }' \
| sed 's/.*://' | sort | uniq | grep -q "$local_port"
2023-10-29 17:28:47 +01:00
}
2023-04-13 00:04:20 +02:00
2023-10-29 17:28:47 +01:00
# Branchement principal
if ! is_forwarding_active; then
start_forwarding
2023-06-17 19:04:53 +02:00
else
2023-10-29 17:28:47 +01:00
stop_forwarding
2023-06-17 19:04:53 +02:00
fi