我努力成为 一名 学者。
写这个脚本之前,自己对于shell脚本,涉及很少。 如果不当之处,还望不吝指教。
#! /bin/bash
############################ 生成 SSH 公钥密钥 ##########################
expect << EOF
spawn ssh-keygen -t rsa
expect "Enter file in which to save the key (/root/.ssh/id_rsa):" { send "\r" }
expect "Enter passphrase (empty for no passphrase):" { send "\r" }
expect "Enter same passphrase again:" {send "\r"}
expect eof
EOF
############################ 配置 集群节点免密登陆 ######################
## 获取本机 IP 地址
IP=`ifconfig eth0 | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2 }' | tr -d addr:]`
## 打印
echo $IP
## 集群地址 密码 我在这里使用 主机名,并已配置 hosts。
servers="master slave1 slave2"
password="123456"
## 获取当前主机 主机名
hostname=`hostname`
startname="master"
## 配置免密登录
auto_copy(){
expect << eof
spawn ssh-copy-id $1
expect {
"(yes/no)" { send "yes\r"; exp_continue; }
"*assword:" { send $2\r }
}
expect eof
eof
}
## 复制 脚本 到集群节点
copy_target_host(){
expect << eof
spawn scp /root/ssh-deploye.sh root@$1:/root
expect {
"(yes/no)" { send "yes\r"; exp_continue; }
"*assword:" {send $2\r }
}
expect eof
eof
}
## 执行 部署脚本
execute_script(){
expect << eof
spawn ssh root@$1 sh /root/ssh-deploye.sh
expect {
"(yes/no)" { send "yes\r"; exp_continue; }
"*assword:" {send $2\r }
}
expect eof
eof
}
for server in $servers
do
if [ $hostname = $startname ]
then
echo "脚本起始执行节点 ${hostname},拷贝脚本 至 其余集群节点。 "
if [ $server == $startname ]
then
echo "自己不拷贝"
else
echo "拷贝节点 $server"
copy_target_host $server $password
execute_script $server $password
fi
else
echo "集群节点 ${hostname} "
fi
# 执行部署脚本
auto_copy $server $password
done