Réécriture : logiciel ssh-fwd

This commit is contained in:
Hippolyte Chauvin 2023-06-17 19:04:53 +02:00
parent 5930748fe5
commit 067d6f722d

View file

@ -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