通常我们会用Ansible或类似的自动化工具来维护和管理多个虚拟机,但如果我们对多个虚拟机的操作是一次性的,不想安装Ansible,可以使用下面的简单的脚本,在远程虚拟机上无限执行命令。
#!/bin/bash
# 1. Check if sshpass is installed
if ! command -v sshpass &> /dev/null; then
echo "Error: sshpass command not found. Please install it (e.g., sudo apt install sshpass)"
exit 1
fi
# Define the list of Virtual Machines
HOSTS=(
"ubuntu@172.25.255.28"
"ubuntu@172.25.255.31"
"ubuntu@172.25.255.90"
)
# 2. Input password once before entering the loop
read -s -p "Please input password (enter once for session): " PASSWORD
echo ""
if [ -z "$PASSWORD" ]; then
echo "Error: Password cannot be empty."
exit 1
fi
# 3. Start the infinite loop for continuous execution
while true; do
echo "----------------------------------------"
echo "Available hosts: ${#HOSTS[@]}"
read -p "Please input the command (type 'exit' to quit): " COMMAND
# Check if user wants to exit the script
if [ "$COMMAND" == "exit" ] || [ "$COMMAND" == "quit" ]; then
echo "Exiting script..."
break
fi
# Prevent empty command execution
if [ -z "$COMMAND" ]; then
echo "⚠️ Command cannot be empty. Please try again."
continue
fi
echo "" # Empty line for formatting
# 4. Loop through hosts and execute
for host in "${HOSTS[@]}"; do
echo "🚀 Executing on $host: $COMMAND"
# Execute command via SSH
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 "$host" "sudo $COMMAND"
# Check execution result
if [ $? -eq 0 ]; then
echo "✅ $host execution successful"
else
echo "❌ $host execution failed (check password, network, or host status)"
# Note: We do not exit here, allowing the loop to continue to the next host
fi
echo ""
done
echo "----------------------------------------"
echo "Batch execution finished. Ready for next command."
echo ""
done
# 5. Cleanup and exit
unset PASSWORD
echo "Script terminated safely."
琼杰笔记






评论前必须登录!
注册