2023-04-13 00:04:20 +02:00
|
|
|
#!/bin/bash -e
|
|
|
|
|
|
|
|
shopt -s expand_aliases
|
|
|
|
[[ $TERM = xterm-kitty ]] && alias ssh='kitty +kitten ssh'
|
|
|
|
|
|
|
|
# Variables
|
|
|
|
ssh=ssh
|
|
|
|
declare -a args
|
|
|
|
|
|
|
|
# Display the usage
|
|
|
|
function usage {
|
|
|
|
cat << EOF
|
|
|
|
Usage: $(basename "$0") SSH_HOST LOCAL_PORT DISTANT_PORT [TARGET] [-- SSH_OPTIONS]
|
|
|
|
EOF
|
|
|
|
}
|
|
|
|
|
2023-05-05 20:10:39 +02:00
|
|
|
# Show an error
|
2023-04-13 00:04:20 +02:00
|
|
|
function error {
|
|
|
|
>&2 usage
|
|
|
|
exit "${1:-1}"
|
|
|
|
}
|
|
|
|
|
2023-05-05 20:10:39 +02:00
|
|
|
# Check if TCP port number is free
|
|
|
|
port_is_free() {
|
|
|
|
! lsof -i -P -n | grep -q ':'"${1}"' (LISTEN)'
|
|
|
|
}
|
|
|
|
|
2023-04-13 00:04:20 +02:00
|
|
|
# Arguments
|
|
|
|
while [[ -n $* ]]; do
|
|
|
|
case "$1" in
|
|
|
|
"--")
|
|
|
|
shift
|
|
|
|
ssh_options=("$@")
|
|
|
|
set --
|
|
|
|
;;
|
|
|
|
*)
|
|
|
|
args+=("$1")
|
|
|
|
shift
|
|
|
|
;;
|
|
|
|
esac
|
|
|
|
done
|
|
|
|
|
|
|
|
# Checking the validity of the args
|
|
|
|
[[ -z ${args[2]} ]] && error 1
|
|
|
|
[[ -z ${args[3]} ]] && args[3]=localhost
|
|
|
|
|
|
|
|
# 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
|
2023-05-05 20:10:39 +02:00
|
|
|
if port_is_free "${args[1]}"; then
|
|
|
|
"${ssh_com[@]}"
|
|
|
|
else
|
|
|
|
echo "Port is not free, skipping."
|
|
|
|
fi
|
2023-04-13 00:04:20 +02:00
|
|
|
|