From 067d6f722d17af346af5d241d07ab8d74df4815c Mon Sep 17 00:00:00 2001 From: Hippolyte Chauvin Date: Sat, 17 Jun 2023 19:04:53 +0200 Subject: [PATCH] =?UTF-8?q?R=C3=A9=C3=A9criture=20:=20logiciel=20ssh-fwd?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/ssh-fwd | 87 +++++++++++++++++++++++++++-------------------------- 1 file changed, 45 insertions(+), 42 deletions(-) diff --git a/bin/ssh-fwd b/bin/ssh-fwd index 0f8e8d2..0f5c81b 100755 --- a/bin/ssh-fwd +++ b/bin/ssh-fwd @@ -1,64 +1,67 @@ -#!/bin/bash -e +#!/bin/bash -shopt -s expand_aliases -[[ $TERM = xterm-kitty ]] && alias ssh='kitty +kitten ssh' +# Alias si le terminal est kitty +if [ "$TERM" = xterm-kitty ]; then + ssh=(kitty +kitten ssh) +else + ssh=(ssh) +fi # Variables -ssh=ssh declare -a args -# Display the usage -function usage { +# Foncitons +error() { + >&2 printf '\033[1;31m%s\033[0m \033[1m%s\033[0m\n' ERROR: "$*" +} + +help() { + local name + name="$(basename "$0")" cat << EOF -Usage: $(basename "$0") SSH_HOST LOCAL_PORT DISTANT_PORT [TARGET] [-- SSH_OPTIONS] +${name}: utilisation: + ${name} SERVEUR PORT_LOCAL PORT_DISTANT [CIBLE] [-- ARGUMENTS_SSH...] EOF } -# Show an error -function error { - >&2 usage - exit "${1:-1}" +error_help() { + error "Invalid usage" + >&2 help + exit 1 } -# Check if TCP port number is free -port_is_free() { - ! lsof -i -P -n | grep -q ':'"${1}"' (LISTEN)' +requested_port_bridge_pid() { + lsof -nP -i TCP -s TCP:LISTEN | awk '($1 == "ssh" && $9 ~ /.*:'"${1}"'/) { print $2 }' | uniq | head -n 1 } -# Arguments -while [[ -n $* ]]; do +# Analyser les arguments +while [ -n "$1" ]; do case "$1" in - "--") - shift - ssh_options=("$@") - set -- - ;; + --) + break + ;; *) args+=("$1") shift - ;; + ;; esac done -# Checking the validity of the args -[[ -z ${args[2]} ]] && error 1 -[[ -z ${args[3]} ]] && args[3]=localhost +# Il doit y avoir au moins 3 arguments dans le tableau +if [ "${#args[@]}" -lt 3 ]; then + error_help +fi -# Command building -ssh_com=( - "$ssh" - "${ssh_options[@]}" - -f - -N - -L "${args[1]}:${args[3]}:${args[2]}" - "${args[0]}" -) - -# Debug -#echo "${ssh_com[@]}" -#exit 0 - -# Execution -set -x -"${ssh_com[@]}" +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]}" +else + echo "Suppression de la redirection..." + kill "$pid" +fi