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
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 # Supprimer la redirection SSH
while [ -n "$1" ]; do stop_forwarding() {
case "$1" in start_forwarding -O cancel
--) }
shift
break
;;
*)
args+=("$1")
shift
;;
esac
done
# Il doit y avoir au moins 3 arguments dans le tableau # Retourner 0 si le port de la redirection est déjà utilisé par SSH
if [ "${#args[@]}" -lt 3 ]; then is_forwarding_active() {
error_help lsof -i -P -n \
fi | awk '($1 == "ssh" && $10 == "(LISTEN)") { print $9 }' \
| cut -d : -f 2 \
| grep -q "$local_port"
}
pid="$(requested_port_bridge_pid "${args[1]}")" # Branchement principal
if [ -z "$pid" ]; then if ! is_forwarding_active; then
exec "${ssh[@]}" \ start_forwarding
-f \
-N \
-L "${args[1]}:${args[3]:-localhost}:${args[2]}" \
"${args[0]}" \
"$@"
else else
echo "Suppression de la redirection..." stop_forwarding
kill "$pid"
fi fi