- 确保每台机子的ip都配置成静态ip
- 确保每台机子都能上网或者yum的源是本地源
- 脚本前面内容的ip和网段自行更改成自已设置的ip以及服务器的密码也是如此
#!/bin/bash
password=123
hostnames=(master node1 node2)
ips=(110 111 112)
ip_prefix=192.168.1
if [ ! $(rpm -qa expect) ]
then
yum install -y expect &>/dev/null
[ $? -ne 0 ] && echo ">>>>>>>> install expect fail " && exit
fi
for ((i=0; i<${#ips[@]}; i++))
do
str_commands+="$ip_prefix.${ips[$i]} ${hostnames[$i]}"
str_hosts+="${hostnames[$i]}"
if [ $i -lt $(( ${#ips[@]} -1 )) ]
then
str_commands+=" $'\n'"
str_hosts+="|"
fi
done
for ((i=0; i<${#ips[@]}; i++))
do
expect <<-EOF
spawn ssh root@$ip_prefix.${ips[$i]}
expect {
"(yes/no)?" {send "yes\r"; exp_continue}
"password:" {send "$password\r"; exp_continue}
}
expect "#"
send "rm -rf .ssh && mkdir .ssh\r"
expect "#"
send "sed -i -E '/$str_hosts/d' /etc/hosts \r"
expect "#"
send "echo -e $str_commands >> /etc/hosts \r"
send "ssh-keygen -t rsa -P \"\" -f .ssh/id_rsa &>/dev/null \r"
send "hostnamectl set-hostname ${hostnames[$i]}\r"
expect "#"
send "exit \r"
expect eof
EOF
done
servers_str=$(IFS=" ";echo "${hostnames[*]}")
for ((i=0; i<${#ips[@]}; i++))
do
expect <<-EOF
set servers [split "$servers_str" " "]
spawn ssh root@$ip_prefix.${ips[$i]}
expect {
"(yes/no)?" {send "yes\r"; exp_continue}
"password:" {send "$password\r"; exp_continue}
}
foreach server \$servers {
expect "#"
send "ssh-copy-id \$server \r"
expect {
"(yes/no)?" {send "yes\r"; exp_continue}
"password:" {send "$password\r"; exp_continue}
}
}
expect "#"
send "exit\r"
expect eof
EOF
done
timeout 5 ssh ${hostnames[0]} 'echo ">>>>>>>>> SSH has passwordless access! <<<<<<<<<<<"'
if [ $? -ne 0 ]
then
'echo ">>>>>>>>> SSH has passwordless Fail! <<<<<<<<<<<"'
exit 1
fi
for host in ${hostnames[@]}
do
ssh -T $host <<EOF
pgrep firewalld &>/dev/null
if [ \$? -eq 0 ]
then
systemctl disable --now firewalld
fi
if [ ! "\$(getenforce)" = "Disabled" ]
then
setenforce 0
sed -i 's/^SELINUX=/cSELINUX=disabled' /etc/selinux/config
fi
sed -i 's|#UseDNS yes|UseDNS no|' /etc/ssh/sshd_config
systemctl restart sshd
exit
EOF
done
脚本执行完成后每台机子需要退出登录,重新登录一次,该脚本主机名更改之后需要在新的bash才能看到更改之后的效果