Skip to content

Instantly share code, notes, and snippets.

@clane9
Created October 17, 2023 14:11
Show Gist options
  • Save clane9/ea3a469e727b6e7f75dc4373e9d2241d to your computer and use it in GitHub Desktop.
Save clane9/ea3a469e727b6e7f75dc4373e9d2241d to your computer and use it in GitHub Desktop.
Multi-hop SSH port forwarding
#!/bin/bash
ssh_forward() {
if [[ $# == 0 || $1 == "-h" || $1 == "--help" ]]; then
echo "Multi-hop SSH port forwarding"
echo
echo "Usage: ssh_forward [--dryrun, -d] --port PORT HOST [HOST2 ...]"
return 1
fi
DRYRUN=
PORT=
HOSTS=()
while (( $# > 0 )); do
case $1 in
--dryrun|-d)
DRYRUN=1
;;
--port)
shift
PORT=$1
;;
*)
HOSTS+=( "$1" )
;;
esac
shift
done
if [[ -z $PORT ]]; then
echo "ERROR: port not specified"
return 1
fi
if [[ ${#HOSTS[@]} == 0 ]]; then
echo "ERROR: no hosts specified"
return 1
fi
NUM_HOSTS=${#HOSTS[@]}
COMMAND=
for (( ii = $NUM_HOSTS - 1; ii >= 0; ii-- )); do
FLAGS=$( (( $ii == $NUM_HOSTS - 1 )) && echo "-NL" || echo "-L" )
COMMAND="ssh $FLAGS $PORT:localhost:$PORT ${HOSTS[ii]} $COMMAND"
done
echo "$COMMAND"
if [[ -z $DRYRUN ]]; then
$COMMAND
fi
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment