单台服务器做免密钥登录

#!/bin/bash
##单台服务器做免密钥登录
#2020-11-18
#by xc
. /etc/init.d/functions
USER="root"
IP="192.168.189.54"
PASSWORD="w....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
echo "开始分发密钥....................."
## 分发命令
/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