Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Created August 4, 2025 16:15
Show Gist options
  • Save yetimdasturchi/dca8cf2696f1d1b7b677685695995af9 to your computer and use it in GitHub Desktop.
Save yetimdasturchi/dca8cf2696f1d1b7b677685695995af9 to your computer and use it in GitHub Desktop.
Run commands on remote servers
#!/bin/bash
VPN_SERVER="10.8.0.1"
STATUS_COMMAND="/root/openvpn_status.sh"
output=$(ssh -o BatchMode=yes -o ConnectTimeout=5 root@$VPN_SERVER "$STATUS_COMMAND")
if [[ $? -ne 0 ]]; then
echo "Failed to connect to $VPN_SERVER or run the command."
exit 1
fi
servers=()
while IFS= read -r line; do
if [[ "$line" =~ ^[-]+$ || "$line" =~ ^Client[[:space:]]+Tunnel ]]; then
continue
fi
client=$(echo "$line" | awk '{print $1}')
if [[ -n "$client" ]]; then
servers+=("$client")
fi
done <<< "$output"
if [[ -z "$1" ]]; then
echo "Usage: $0 '<remote_command>'"
exit 1
fi
CLIENT_COMMAND="$1"
for server in "${servers[@]}"; do
echo "→ Running on $server..."
output=$(ssh -o BatchMode=yes \
-o ConnectTimeout=5 \
-o ConnectionAttempts=1 \
-o StrictHostKeyChecking=accept-new \
"$server" "$CLIENT_COMMAND" 2>&1)
ssh_status=$?
if [[ $ssh_status -ne 0 ]]; then
echo "[ERROR] $server: SSH failed with error:"
echo "$output"
else
echo "[OK] $server:"
echo "$output"
fi
echo "----------------------------------------"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment