Skip to content

Instantly share code, notes, and snippets.

@cyberbutler
Created August 1, 2024 13:28
Show Gist options
  • Save cyberbutler/8fbcca7afbacb5f1d39418005dcdc103 to your computer and use it in GitHub Desktop.
Save cyberbutler/8fbcca7afbacb5f1d39418005dcdc103 to your computer and use it in GitHub Desktop.
Execute a command against one, or multiple SSM connected systems, return the output and exit
#!/bin/bash
run_command() {
ident=$1
cmd=$2
>&2 echo "[+] Sending command to :: $i";
params='{"command": ["'$cmd'"]}'
# Read why unbuffer is needed here: https://github.com/aws/amazon-ssm-agent/issues/354
unbuffer aws ssm start-session --document-name 'AWS-StartNonInteractiveCommand' --parameters "$params" --target $ident
}
all() {
command=${1:-hostname}
platform=${2:-Linux}
aws ssm get-inventory | jq '.Entities[] | .Data["AWS:InstanceInformation"] | select (. != null) | .Content[] | select(.InstanceStatus != "Terminated") | select(.PlatformType == "'$platform'") | "\(.PlatformType) \(.IpAddress) \(.ComputerName) \(.InstanceId)"' -r | sort -u | \
while read i; do
ident=$(echo $i | awk '{print $4}');
echo $i;
run_command $ident "$command";
sleep 1;
done
}
if [ $1 = "all" ]; then
all "$2" $3
else
run_command $1 $2
fi
# Usage:
# ./execute-ssm-command.sh all 'hostname' [Linux | Windows]
#
# OR target a single system
#
# ./execute-ssm-command.sh i-123456789012 'command'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment