ssh免密验证,shell批量设置

#!/bin/sh
#ssh免密验证,shell批量设置#


. /etc/init.d/functions
[[ -f /usr/bin/expect ]] || { echo " install expect ...";yum install expect -y >/dev/null 2>&1; } #若没expect则安装#
[ $? = 0 ] || { echo "expect安装失败";exit; } #安装失败则退出#
PUB=/$HOME/.ssh/id_dsa #公钥路径#

USER=root   #登录用户#
PASS=123321 #登录密码#
echo  >>my.sh.conf  #防止没有出错#
source ./my.sh.conf  >/dev/null 2>&1 #加载自定义#
[[ -f $PUB ]] || { ssh-keygen -t dsa -P "" -f $PUB >/dev/null 2>&1; } #若没公钥则生成#

#expect自动交互
function EXP() {
/usr/bin/expect << EOF
set timeout 5
spawn /usr/bin/ssh-copy-id -i $PUB.pub  $USER@$n
expect {
        "*yes/no*" { send "yes
";exp_continue }
        "password:" { send "$PASS
";exp_continue } 
        eof { exit }
        }
EOF
}
#
for n in $*
do
  EXP >/dev/null 2>&1
  ssh $n hostname >/dev/null 2>&1
  [[ $? == 0 ]] && action "========$n" /bin/true || action "========$n" /bin/false
done

exit
###########################
# #使用实例#

#编写shell #
 vim sshkey.me.sh
#自定义认证用户及密码#
echo "
USER=root
PASS=root2018
">my.sh.conf

#hosts设置(可选,可直接使用IP)#
echo "
192.168.8.21   node1
192.168.8.22   node2
">>/etc/hosts

#执行shell文件,ssh批量认证#
sh ./sshkey.me.sh node1 node2

###########################

  

原文地址:https://www.cnblogs.com/kcxg/p/10503473.html