创建 /root/host_list 文件,内容如下:分别是IP地址、用户、密码、用户的家目录、主机名
192.168.88.101 root 123456 /root node1
192.168.88.102 root 123456 /root node2
192.168.88.103 root 123456 /root node3
核心的执行脚本内容如下:
#!/bin/bash
# 每台服务器生成 rsa 加密文件,并把 rsa 文件汇总到执行脚本的机器上
while read line; do
ip=`echo $line | cut -d " " -f1` # 提取文件中的ip
user=`echo $line | cut -d " " -f2` # 提取文件中的用户名
passwd=`echo $line | cut -d " " -f3` # 提取文件中的密码
home=`echo $line | cut -d " " -f4` # 提取文件中的家目录
/usr/bin/expect <<-EOF
spawn ssh ${user}@${ip} rm -rf ${home}/.ssh/*
expect {
"*y/n*" {send "y\r";exp_continue }
"*yes/no*" {send "yes\r";exp_continue }
"*password*" {send "${passwd}\r";exp_continue}
"Overwrite*" {send "y\r";exp_continue}
"Enter file in which to save the key*" { send "\r"; exp_continue}
"Enter passphrase*" {send "\r";exp_continue }
"Enter same passphrase again*" {send "\r"; exp_continue }
}
spawn ssh ${user}@${ip} ssh-keygen -t rsa
expect {
"*y/n*" { send "y\r";exp_continue }
"*yes/no*" { send "yes\r";exp_continue }
"*password*" { send "${passwd}\r";exp_continue}
"Overwrite*" { send "y\r";exp_continue}
"Enter file in which to save the key*" { send "\r"; exp_continue}
"Enter passphrase*" { send "\r";exp_continue }
"Enter same passphrase again*" { send "\r"; exp_continue }
}
spawn scp ${user}@${ip}:${home}/.ssh/id_rsa.pub /tmp/only-${ip}.pub
expect {
"*yes/no*" {send "yes\r";exp_continue}
"*password*" {send "${passwd}\r";exp_continue}
}
EOF
done < /root/host_list
# 将所有机器的 id_rsa.pub 内容都放置到 authorized_keys 中
while read line; do
ip=`echo $line | cut -d " " -f1`
home=`echo $line | cut -d " " -f4`
cat /tmp/only-${ip}.pub >> ${home}/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
done < /root/host_list
# 将 authorized_keys 放入到每台服务器主机的 ~/.ssh/ 目录下,同时生成多个集群的公钥指纹文件 known_hosts
while read line; do
ip=`echo $line | cut -d " " -f1`
user=`echo $line | cut -d " " -f2`
passwd=`echo $line | cut -d " " -f3`
home=`echo $line | cut -d " " -f4`
host=`echo $line | cut -d " " -f5`
/usr/bin/expect <<EOF
spawn scp ${home}/.ssh/authorized_keys ${user}@${ip}:${home}/.ssh/
expect {
"*yes/no*" {send "yes\r";exp_continue}
"*password*" {send "${passwd}\r";exp_continue}
}
EOF
ssh-keyscan -H ${ip} >> ${home}/.ssh/known_hosts
ssh-keyscan -H ${host} >> ${home}/.ssh/known_hosts
done < /root/host_list
# 将 known_hosts 放入到每台服务器主机的 ~/.ssh/ 目录下
while read line; do
ip=`echo $line | cut -d " " -f1`
user=`echo $line | cut -d " " -f2`
home=`echo $line | cut -d " " -f4`
/usr/bin/expect <<EOF
spawn scp ${home}/.ssh/known_hosts ${user}@${ip}:${home}/.ssh/
expect {
"*yes/no*" {send "yes\r";exp_continue}
}
EOF
done < /root/host_list