Skip to content

Instantly share code, notes, and snippets.

@nathandines
Last active May 1, 2020 03:17
Show Gist options
  • Save nathandines/d64ce274ac24e4accaeaf14cbb78edce to your computer and use it in GitHub Desktop.
Save nathandines/d64ce274ac24e4accaeaf14cbb78edce to your computer and use it in GitHub Desktop.
SSH Session via AWS Session Manager with SSH Agent Passthrough
#!/usr/bin/env bash
set -euo pipefail
randomPort="$((49152 + ($RANDOM % 16383)))"
function cleanup_jobs() {
for i in $(jobs -p); do
pkill -P $i
done
}
trap cleanup_jobs EXIT
if [ "${1-x}" == 'x' ]; then
echo 'Please pass an instance ID as the first parameter to this command (e.g. [<user>@]<instance-id>)' 1>&2
exit 1
fi
fullTarget="$1"
userField="${fullTarget%%@*}"
instanceField="${fullTarget#*@}"
aws ssm start-session --target "$instanceField" \
--document-name AWS-StartPortForwardingSession \
--parameters "portNumber=22,localPortNumber=${randomPort}" &
sshArgs=('-o' 'ForwardAgent=yes' '-p' "$randomPort" '-o' 'StrictHostKeyChecking=no' '-o' 'UserKnownHostsFile=/dev/null')
if [ "$userField" != "$instanceField" ]; then
sshArgs+=('-l' "$userField")
fi
while :; do
nc -z localhost $randomPort && break || sleep 1
done
sleep 5
ssh "${sshArgs[@]}" localhost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment