#!/bin/bash error() { >&2 printf '\033[1;31mERROR:\033[0m \033[1m%s\033[0m\n' "$error" return "$1" } error_null_arg() { local error error="Argument \"${arg_name}\" can't be null" error 1 } # Lancer la redirection SSH start_forwarding() { ssh \ -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 }' \ | sed 's/.*://' | sort | uniq | grep -q "$local_port" } step() { printf '\033[1;32m*\033[0m \033[1m%s...\033[0m\n' "$*" } # Parser les variables trap error_null_arg EXIT set -e arg_name='SSH host' ; ssh_host="$1" ; shift arg_name='local port' ; local_port="$1" ; shift arg_name='distant port'; distant_port="$1"; shift trap - EXIT unset arg_name if [ -n "$1" ] then target="$1" else target=localhost fi set +e # Branchement principal if ! is_forwarding_active; then step "Starting the redirection" start_forwarding else step "Stopping the redirection" stop_forwarding fi