#!/bin/bash
#==========================================
#脚本名称： host_ssh_login.sh
#脚本作者：     WHao
#脚本版本：  v0.1
#创建时间： 2025-05-30
#联系方式:  whaoy86@163.com
#脚本用途：  基于sshpass 对主机免密登录
#=========================================
SSH_USER=root
SSH_PASS=123456
SSH_PORT=22
slave_ips=(10.0.0.15 10.0.0.31 10.0.0.32)

# 颜色输出
color() {
    local msg="$1"
    local status="$2"
    local label color

    case "$status" in
        success|0) label="  OK  "; color="1;32" ;;
        failure|1) label="FAILED"; color="1;31" ;;
        *)         label=" WARN "; color="1;33" ;;
    esac

    printf "%-40s \033[60G[\033[%sm%s\033[0m]\n" "$msg" "$color" "$label"
}

#下载sshpass
if ! command -v sshpass &> /dev/null; then
    . /etc/os-release
    if [[ "$ID" == "centos" || "$ID" == "rocky" ]]; then
        yum install -y sshpass || {
            color "sshpass安装失败"  1
            exit 1
        }
        setenforce 0 && sed -i "s/SELINUX=enforcing/SELINUX=disabled/g " /etc/selinux/config
        
    elif [[ "$ID" == "ubuntu" ]]; then
        apt update >/dev/null
        apt install -y sshpass  || {
            color "sshpass安装失败"  1
            exit 1
        }
        
    else
        echo "不支持此操作系统" 
        exit 1
    fi
fi
color "sshpass安装"  $?

# 生成 SSH 密钥（如果不存在）
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa &>/dev/null && color "生成 SSH 密钥"  $?

# 提前收集所有主机的公钥，避免交互确认
for ip in "${slave_ips[@]}"; do
    ssh-keyscan -p $SSH_PORT $ip >> ~/.ssh/known_hosts  &>/dev/null
done
color "收集主机公钥"  $?

# 使用 sshpass 配置免密登录
for ip in "${slave_ips[@]}"; do
    color "$ip 配置免密登录"  $?
    sshpass -p "$SSH_PASS" ssh-copy-id -p $SSH_PORT -o StrictHostKeyChecking=no $SSH_USER@$ip  &>/dev/null
    sshpass -p "$SSH_PASS" ssh -p $SSH_PORT -o StrictHostKeyChecking=no $SSH_USER@$ip "echo '成功连接到 $ip!'"  &>/dev/null
done
