Skip to content

Instantly share code, notes, and snippets.

@blkdr
Last active December 6, 2021 20:10
Show Gist options
  • Save blkdr/86b25213df760e2d71d8d583ac30d438 to your computer and use it in GitHub Desktop.
Save blkdr/86b25213df760e2d71d8d583ac30d438 to your computer and use it in GitHub Desktop.
SSH connection with port forwarding powers
  1. Copy to a file like connect.sh in your home (~/).
  2. Update the local variables such as LOCAL_HOST, REMOTE_USER, REMOTE_HOST and PEM_FILE.
  3. Make it executable with $ chmod +x ~/connect.sh
  4. To run:
  • Without ports $ ./connect.sh
  • With ports $ ./connect.sh 8080 8081 ... (you can add several ports separated by spaces)
#!/bin/bash
LOCAL_HOST="localhost" # Where you want to forward the ports
REMOTE_USER="ubuntu" # The remote user on the IP you want to connect
REMOTE_HOST="192.0.XY.XYZ" # IP you want to connect
PEM_FILE="~/my-top-secret.pem" # Path to your PEM file
PORTS_LEGEND="Connecting to remote host «$REMOTE_HOST»"
FORMATTED_PORTS=""
if [ $# == 0 ]; then
PORTS_LEGEND+=" without port forward"
else
PORTS_LEGEND+=" with port forward on:"
fi
for PORT in $@; do
PORTS_LEGEND+=" «$PORT»"
FORMATTED_PORTS+=" -L \"$PORT:$LOCAL_HOST:$PORT\""
done
echo "$PORTS_LEGEND"
eval "ssh -x -C -Y -4 -i $PEM_FILE$FORMATTED_PORTS $REMOTE_USER@$REMOTE_HOST"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment