Réécriture en cours de ssh-fwd

This commit is contained in:
Hippolyte Chauvin 2023-10-29 17:28:47 +01:00
parent c637cd7dd7
commit 9ff68dda52

View file

@ -1,68 +1,59 @@
#!/bin/bash
# Alias si le terminal est kitty
if [ "$TERM" = xterm-kitty ]; then
ssh=(kitty +kitten ssh)
else
ssh=(ssh)
fi
# Variables
declare -a args
# Foncitons
error() {
>&2 printf '\033[1;31m%s\033[0m \033[1m%s\033[0m\n' ERROR: "$*"
>&2 printf '\033[1;31mERROR:\033[0m \033[1m%s\033[0m\n' "$error"
return "$1"
}
help() {
local name
name="$(basename "$0")"
cat << EOF
${name}: utilisation:
${name} SERVEUR PORT_LOCAL PORT_DISTANT [CIBLE] [-- ARGUMENTS_SSH...]
EOF
error_null_arg() {
local error
error="Variable \"${1}\" can't be null"
error 1
}
error_help() {
error "Invalid usage"
>&2 help
exit 1
parse_variable() {
! :
}
requested_port_bridge_pid() {
lsof -nP -i TCP -s TCP:LISTEN | awk '($1 == "ssh" && $9 ~ /.*:'"${1}"'/) { print $2 }' | uniq | head -n 1
# 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"
}
# Analyser les arguments
while [ -n "$1" ]; do
case "$1" in
--)
shift
break
;;
*)
args+=("$1")
shift
;;
esac
done
# Supprimer la redirection SSH
stop_forwarding() {
start_forwarding -O cancel
}
# Il doit y avoir au moins 3 arguments dans le tableau
if [ "${#args[@]}" -lt 3 ]; then
error_help
fi
# 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 }' \
| cut -d : -f 2 \
| grep -q "$local_port"
}
pid="$(requested_port_bridge_pid "${args[1]}")"
if [ -z "$pid" ]; then
exec "${ssh[@]}" \
-f \
-N \
-L "${args[1]}:${args[3]:-localhost}:${args[2]}" \
"${args[0]}" \
"$@"
# Branchement principal
if ! is_forwarding_active; then
start_forwarding
else
echo "Suppression de la redirection..."
kill "$pid"
stop_forwarding
fi