Last active
May 1, 2020 03:17
-
-
Save nathandines/d64ce274ac24e4accaeaf14cbb78edce to your computer and use it in GitHub Desktop.
SSH Session via AWS Session Manager with SSH Agent Passthrough
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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