安装tcl、expect相关运行软件:
# CentOS系统
yum install tcl -y
yum install expect -y
# Ubuntu系统
sudo apt install tcl -y
sudo apt install expect -y
一键免密配置脚本需要每台服务器的用户名和密码保持一致,以下为shell脚本:
#!/bin/bash
if [ "$#" -lt 2 ]; then
echo "Usage:./generate_ssh_key.sh [user] [password]"
exit 2
fi
user=$1
password=$2
hosts="slave1.bigdata.com slave2.bigdata.com slave3.bigdata.com slave4.bigdata.com"
echo "================= 程序开始运行 ==================="
for host in ${hosts}
do
echo ================= $host ===================
expect -c "
set timeout 2;
spawn ssh ${user}@$host
expect {
*yes/no* { send \"yes\\n\"; exp_continue; }
*password* { send \"${password}\\n\" }
}
sleep 1
send \"ssh-keygen -t rsa\\n\"
expect {
*id_rsa* { send \"\\n\"; exp_continue; }
*y/n* {set timeout 5; send \"y\\n\"; exp_continue; }
*passphrase* {set timeout 5; send \"\\n\"; exp_continue; }
*again* {set timeout 5; send \"\\n\" }
}
sleep 1
foreach target {${hosts}} {
send \"ssh-copy-id \$target\\n\"
expect {
*connecting* {set timeout 5; send \"yes\\n\"; exp_continue;}
*password* {set timeout 5; send \"${password}\\n\";}
}
sleep 1
}
"
done
echo "================= 程序结束运行 ==================="
user=免密登录用户
password=免密登录用户密码
hosts=需要配置免密登录的服务器
注意:需要保持免密登录用户
的文件权限为750,免密登录用户下的.ssh
文件权限为700。