#!/bin/bash
set -e
#所需变量
#取得集群的所有主机名,这里需要注意:/etc/hosts配置的IP和主机名只能用一个空格分割
hostList=$(cat /etc/hosts | tail -n +2 | cut -d ' ' -f 2)
pingCount=5
logPre=TDP
#服务器密码
passwd=xxxx
set timeout 60
#秘钥生成函数
ssh-keygen(){
echo "======>$host ssh-keygen...
"
/usr/bin/expect <<EOF
spawn ssh-keygen
expect {
"Enter file in which to save the*" { send "
"; exp_continue}
"Overwrite*" { send "n
" ; exp_continue}
"Enter passphrase*" { send "
"; exp_continue}
"Enter same passphrase again:" { send "
" ; exp_continue}
}
EOF
}
#拷贝公钥函数
ssh-copy-id(){
echo "======>$host ssh-copy-id...
"
/usr/bin/expect <<EOF
spawn ssh-copy-id $host
expect {
"*yes/no*" {send "yes
" ; exp_continue}
"*password*" {send "$passwd
" ; exp_continue}
}
EOF
}
ssh-keygen
for host in $hostList
doecho "----------------$host-----------------"
#检测主机的连通性
unPing=$(ping $host -c $pingCount | grep 'Unreachable' | wc -l)
if [ "$unPing" == "$pingCount" ]; then
echo -e "$logPre======>$host is Unreachable,please check '/etc/hosts' file"
continue
fi
echo "$logPre======>$host "
ssh-copy-id $host
echo "$logPre======>$host is done! "
done
wait
echo "------hosts done--------"