1、提前安装依赖
[alex@hadoop102 ~]$ sudo yum install -y sshpass expect -y
2、编辑脚本
[alex@hadoop102 ~]$ touch ~/bin/auto_ssh_two_expect.sh
[alex@hadoop102 ~]$ chmod 755 ~/bin/auto_ssh_two_expect.sh
[alex@hadoop102 ~]$ vim ~/bin/auto_ssh_two_expect.sh
#!/bin/bash
user=`whoami`
passwd=000000
for((host=102; host<=104; host++));do
sshpass -p $passwd ssh -q -o StrictHostKeyChecking=no ${user}@hadoop${host} "rm -rf ~/.ssh/*"
done
for((host=102; host<=104; host++));do
sshpass -p $passwd ssh -q -o StrictHostKeyChecking=no ${user}@hadoop${host} "sudo yum install -y sshpass expect -y"
done
# sudo yum install -y sshpass expect -y
for((host=102; host<=104; host++));do
sshpass -p $passwd ssh -q -o StrictHostKeyChecking=no ${user}@hadoop${host} expect << EOF
spawn ssh-keygen -t rsa
expect {
"Enter file in which to save the key (/home/${user}/.ssh/id_rsa):" { send "\r"; exp_continue}
"Overwrite (y/n)?" { send "y\r"; exp_continue }
"Enter passphrase (empty for no passphrase):" { send "\r"; exp_continue}
"Enter same passphrase again:" { send "\r"}
}
expect eof
EOF
done
for((current=102; current<=104; current++));do
for((host=102; host<=104; host++));do
sshpass -p $passwd ssh -q -o StrictHostKeyChecking=no ${user}@hadoop${current} "sshpass -p $passwd ssh-copy-id -o StrictHostKeyChecking=no ${user}@hadoop${host}"
done
done
3、执行脚本
[alex@hadoop102 ~]$ auto_ssh_two_expect.sh