Skip to content

Instantly share code, notes, and snippets.

@ajkerrigan
Created July 9, 2020 03:28
Show Gist options
  • Save ajkerrigan/8e720ce7d359256eecdcef43a154ac10 to your computer and use it in GitHub Desktop.
Save ajkerrigan/8e720ce7d359256eecdcef43a154ac10 to your computer and use it in GitHub Desktop.
Start Mosh with AWS SSM Session Manager
#!/bin/bash
#
# Mush mosh and SSM sessions together.
#
# Run mosh-server on an EC2 instance as part of an AWS Session Manager SSH
# session, and feed the output into mosh-client locally. This is helpful
# if you have an EC2 instance which:
#
# * Is publicly addressable
# * Has a predictable Name tag but a shifting IP
# * Allows inbound Mosh traffic (UDP 60000-61000) from your location
# * Does not allow inbound SSH, except via SSM
#
# Dependencies:
#
# * AWS CLI
# * jq
# * mosh (on both the client and server)
set -euo pipefail
usage() {
echo "Usage: $0 -p <AWS CLI profile> -n <instance name filter> -r <region> -u <remote user>"
}
help() {
echo -e "Start a mosh session on an EC2 instance via AWS SSM Session Manager.\n"
usage
}
while getopts ":hp:n:r:u:" options; do
case "${options}" in
h)
help; exit 0;;
p)
PROFILE=${OPTARG};;
n)
NAME_FILTER=${OPTARG};;
r)
REGION=${OPTARG};;
u)
REMOTE_USER=${OPTARG};;
:)
echo -e "Error: -${OPTARG} requires an argument.\n"
usage; exit 1;;
*)
echo -e "Unknown option -${OPTARG}.\n"
usage; exit 1;;
esac
done
if [[ -z "$PROFILE" || -z "$NAME_FILTER" || -z "$REMOTE_USER" || -z "$REGION" ]]; then
help
exit 1
fi
shift $((OPTIND - 1))
target_instance=$(
aws ec2 describe-instances \
--profile "${PROFILE}" \
--region "${REGION}" \
--filter "Name=tag:Name,Values=[${NAME_FILTER}]"
)
target_instance_ip=$(jq -nr "$target_instance | .Reservations[].Instances[].PublicIpAddress")
target_instance_id=$(jq -nr "$target_instance | .Reservations[].Instances[].InstanceId")
echo "Target instance: $target_instance_id ($target_instance_ip)"
echo "Starting mosh-server..."
output=$(
ssh -o ProxyCommand="aws ssm start-session \
--profile ${PROFILE} \
--region ${REGION} \
--target $target_instance_id \
--document-name AWS-StartSSHSession \
--parameters 'portNumber=22'" \
${REMOTE_USER}@${target_instance_id} /usr/local/bin/mosh-server \
| grep "MOSH CONNECT" | tr -d '\r\n'
)
echo "Getting key/port output..."
echo $output
mosh_port=$(echo $output | cut -d' ' -f3)
mosh_key=$(echo $output | cut -d' ' -f4)
echo "Starting mosh-client on port $mosh_port with key $mosh_key..."
MOSH_KEY="$mosh_key" mosh-client "$target_instance_ip" "$mosh_port"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment