Skip to content

Instantly share code, notes, and snippets.

@jonasjancarik
Created June 29, 2023 13:24
Show Gist options
  • Save jonasjancarik/3c97bed024c864c866df8bf449b245cf to your computer and use it in GitHub Desktop.
Save jonasjancarik/3c97bed024c864c866df8bf449b245cf to your computer and use it in GitHub Desktop.
Run scripts on one more hosts using SSH
#!/bin/bash
set -e
# Ensure we have at least two arguments: the script file and at least one host
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <script_file> <host1> <host2> ... <hostN>"
exit 1
fi
# Get script file and hosts from arguments
SCRIPT_FILE="$1"
shift
HOSTS=("$@")
# Check that script file exists
if [ ! -f "$SCRIPT_FILE" ]; then
echo "Script file $SCRIPT_FILE does not exist"
exit 1
fi
# Read script to run from a file
SCRIPT=$(cat "$SCRIPT_FILE")
# Iterate over each host
for HOST in "${HOSTS[@]}"; do
echo "[$(date)] Deploying to $HOST"
# Check SSH connectivity
if ! ssh -o BatchMode=yes -o ConnectTimeout=5 $HOST echo "SSH connected" > /dev/null 2>&1; then
echo "[$(date)] Cannot connect to $HOST. Skipping..."
continue
fi
# Run script on remote host
if ssh -o BatchMode=yes $HOST "$SCRIPT"; then
echo "[$(date)] Successfully deployed to $HOST"
else
echo "[$(date)] Deployment to $HOST failed"
fi
done
echo "[$(date)] Deployment complete"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment