多台服务器做免密钥登录

#!/bin/bash
##向多台服务器分发自己的公钥
#IP.txt 放在/opt/
#2020-11-18
#by xc
. /etc/init.d/functions
USER="root"
PASSWORD=".....123"
KEYFILE="/root/.ssh/id_rsa.pub"
clear
date
function net_chk(){
#检测有无外网
ping -c 1 114.114.114.114 > /dev/null 2>&1
if [ $? -eq 0 ];then
   echo '网络正常,程序将继续运行。'
   sleep 1
else
   curl www.baidu.com >/dev/null 2>&1
   if [ $? -ne 0 ]; then
     echo '检测到网络连接有异常,请检查您的网络设置.....'
     exit
   else
     echo '网络正常,程序将继续运行.'
     sleep 1
  fi
fi
}

if [ ! -f /root/.ssh/id_rsa.pub ];then
  echo "开始生成密钥对..................."
  ssh-keygen -t rsa -N '' -f /root/.ssh/id_rsa -q
  sleep 2
fi

##判断有没有分发工具expect
if [ ! -f /usr/bin/expect ];then
  echo "正在安装分发工具................."
  net_chk
  yum install expect -y >/tmp/expect.log 2>&1
fi

if [ ! -f /opt/ip.txt ];then
  echo "请将保存服务器IP的文件ip.txt,复制到/opt/后,再重新运行。"
  echo "文件格式最好一个IP占一行"
  sleep 2
  exit
fi
echo "开始分发密钥....................."
##向多台服务器分发自己的公钥
for IP in `cat /opt/ip.txt`
do
## 分发命令
/usr/bin/expect -c "
#expect 利用 spawn 来执行 shell 的命令
spawn ssh-copy-id -i $KEYFILE "$USER@$IP"
expect {
\"yes/no\" {send \"yes\r\";exp_continue}
\"*password\" {send \"$PASSWORD\r\"}
}
expect eof
"
if [ $? -eq 0 ];then
   action "$IP 分发密钥成功" /bin/true
else
   action "$IP 分发密钥失败" /bin/false
fi
done