#!/bin/bash
#***************************************************************#
# ScriptName: mkpublickey.sh
# Author: xhy
# Create Date: 2025-07-01 23:55
# Modify Author: xhy
# Modify Date: 2025-07-16 09:33
# Version: v1
#***************************************************************#

# 检查参数
if [ $# -ne 1 ]; then
    echo "该脚本需要带上主机密码: $0 <密码>"
    exit 1
fi

# 主机列表（直接内置）
HOSTS=(
    172.24.8.11
    172.24.8.12
    172.24.8.13
)
PASSWORD=$1

# 生成SSH密钥
echo "生成SSH密钥..."
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -t rsa -f ~/.ssh/id_rsa -N '' -q

# 安装expect（若未安装）
if ! command -v expect &> /dev/null; then
    echo "安装expect工具..."
    yum install -y expect >/dev/null 2>&1 || apt install -y expect >/dev/null 2>&1
fi

# 批量部署
echo "开始分发密钥到主机..."
for host in "${HOSTS[@]}"; do
    echo -n "开始分发 $host: "
    
    # 关键修复：使用独立expect脚本避免EOF冲突
    expect -c "
        set timeout 15
        spawn ssh-copy-id -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@$host
        expect {
            \"yes/no\" { send \"yes\r\"; exp_continue }
            \"password:\" { send \"$PASSWORD\r\" }
            timeout { exit 1 }
        }
        expect {
            \"try again\" { exit 2 }
            \"Permission denied\" { exit 3 }
            eof { exit 0 }
            timeout { exit 4 }
        }
    " >/dev/null 2>&1
    
    case $? in
        0) echo "✅ 连接成功" ;;
        1) echo "❌ 连接超时" ;;
        2) echo "❌ 密码错误" ;;
        3) echo "❌ 权限被拒绝" ;;
        4) echo "⚠️  操作超时但可能成功" ;;
        *) echo "❌ 未知错误" ;;
    esac
done

echo -e "免密登录配置已完成! 已操作 ${#HOSTS[@]} 台主机！\n" 

sleep 3s
