Created
August 1, 2024 13:28
-
-
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
This file contains hidden or 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
#!/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