ssh免密登录脚本

 

#!/bin/bash
set -e

#所需变量
#取得集群的所有主机名,这里需要注意:/etc/hosts配置的IP和主机名只能用一个空格分割
hostList=$(cat /etc/hosts | tail -n +2 | cut -d ' ' -f 2)
pingCount=5
logPre=TDP

#服务器密码
passwd=xxxx

set timeout 60

#秘钥生成函数
ssh-keygen(){
    echo "======>$host ssh-keygen... \n"
    /usr/bin/expect <<EOF
    spawn ssh-keygen
    expect {
        "Enter file in which to save the*" { send "\r"; exp_continue}
        "Overwrite*" { send "n\r" ; exp_continue}
        "Enter passphrase*" { send "\r"; exp_continue} 
        "Enter same passphrase again:" { send "\r" ; exp_continue}
    }
EOF
}

#拷贝公钥函数
ssh-copy-id(){
    echo "======>$host ssh-copy-id... \n"
    /usr/bin/expect <<EOF
    spawn ssh-copy-id $host
    expect {
        "*yes/no*" {send "yes\r" ; exp_continue}
        "*password*" {send "$passwd\r" ; exp_continue}
    }

EOF
}

ssh-keygen

for host in $hostList
doecho "----------------$host-----------------"
    #检测主机的连通性
    unPing=$(ping $host -c $pingCount | grep 'Unreachable' | wc -l)
    if [ "$unPing" == "$pingCount" ]; then
        echo -e "$logPre======>$host is Unreachable,please check '/etc/hosts' file"
        continue
    fi

    echo "$logPre======>$host  "
   
    ssh-copy-id $host
   echo "$logPre======>$host is done! "

done

wait

echo "------hosts done--------"

 

posted @ 2020-07-01 16:13  鱼丸河粉  阅读(224)  评论(0编辑  收藏  举报