使用expect命令打通所有集群机器

    做分布式系统时候,集群的部署,环境的配备是个麻烦的事情,打通集群算是其中比较基本的事情,也是十分重要的,相对于一台一台机器打通,如果使用脚本一次性打通集群内的所有机器,将会是十分美妙的事情。

    打通集群的关键是两个问题,1、ssh加密的理解2、expect的使用。  关于这两方面的知识我在此不做解释,可以参见 O'Reilly的相关书籍学习。今天分享一下我的关于集群打通的脚本。

    前提:1、安装expect ,可以使用yum install expect   2、在下面脚本中首先要制定machine文件,表示集群中的所有机器名或IP,一行一个

    下面是machine文件  

    192.168.0.5
    192.168.0.6

    下面是exp.sh,用于打通所有集群

     

#!/bin/bash

declare PASSWORD
declare USER

function exp {
expect -c "
set timeout 10
spawn $1
expect {
(yes/no)? {
send yes\r
exp_continue
} *assword: {
send $PASSWORD\r
exp_continue
} eof {
exit
}
}
"
}


function create_newkey {
rm -rf /home/$USER/.ssh
expect -c "
set timeout 10
spawn ssh-keygen -t rsa
expect {
id_rsa) {
send \r
exp_continue
} passphrase) {
send \r
exp_continue
} again: {
send \r
interact

}
}
"
touch /home/$USER/.ssh/authorized_keys
chmod 600 /home/$USER/.ssh/authorized_keys
cat /home/$USER/.ssh/id_rsa.pub>>~/.ssh/authorized_keys
}


function transfer {
while read IP
do
exp "scp -r /home/$USER/.ssh $IP:~/"
done<machine
}

function get_pass {
read -p "Enter the user:" USER
stty -echo
read -p "Enter the password:" PASSWORD
printf "\n"
read -p "Enter again:" PASSWORD1
stty echo
printf "\n"
if [ "$PASSWORD" != "$PASSWORD1" ];then
echo "password inconsistent"
exit 1
else
create_newkey
transfer
ssh-add /home/$USER/.ssh/id_rsa
fi
}

get_pass
原文地址:https://www.cnblogs.com/sidmeng/p/2386070.html