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 #!/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() { 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() { error_null_arg() {
local name local error
name="$(basename "$0")" error="Variable \"${1}\" can't be null"
cat << EOF error 1
${name}: utilisation:
${name} SERVEUR PORT_LOCAL PORT_DISTANT [CIBLE] [-- ARGUMENTS_SSH...]
EOF
} }
error_help() { parse_variable() {
error "Invalid usage" ! :
>&2 help
exit 1
} }
requested_port_bridge_pid() { # Parser les variables
lsof -nP -i TCP -s TCP:LISTEN | awk '($1 == "ssh" && $9 ~ /.*:'"${1}"'/) { print $2 }' | uniq | head -n 1 trap error_null_arg EXIT
} set -e
# Analyser les arguments ssh_host="$1"
while [ -n "$1" ]; do
case "$1" in
--)
shift shift
break
;;
*)
args+=("$1")
shift
;;
esac
done
# Il doit y avoir au moins 3 arguments dans le tableau parse_variable ssh_host "$1" 'SSH host'
if [ "${#args[@]}" -lt 3 ]; then parse_variable local_port 'local port'
error_help parse_variable distant_port 'distant port'
fi
pid="$(requested_port_bridge_pid "${args[1]}")" trap - EXIT
if [ -z "$pid" ]; then set +e
exec "${ssh[@]}" \
-f \ # Lancer la redirection SSH
-N \ start_forwarding() {
-L "${args[1]}:${args[3]:-localhost}:${args[2]}" \ ssh \
"${args[0]}" \ -f -N \
"$@" -L "${local_port}:${target}:${distant_port}" \
"$@" \
"$ssh_host"
}
# Supprimer la redirection SSH
stop_forwarding() {
start_forwarding -O cancel
}
# 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"
}
# Branchement principal
if ! is_forwarding_active; then
start_forwarding
else else
echo "Suppression de la redirection..." stop_forwarding
kill "$pid"
fi fi