shell实现对多台服务器ssh免密登录

系统运维 waitig 419℃ 百度已收录 0评论

管理多台服务器手工执行ssh免密登录有点麻烦,于是写一个shell脚本实现自动化操作,记录以备后续查看。

注意:

需要安装expect

#!/bin/bash
##########################################################
#
# Copyright (2017-10-21, )
#
# Author: charnet1019@163.com
# Last modified: 2017-10-22 00:02
# Description: 实现ssh免密登录
#
##########################################################

# definition IP dictionary array
declare -A IPListDict

LOCAL_IP="192.168.2.3"
USER_NAME="root"

# 主机IP地址和密码,每行一个主机
IPListDict=(
[192.168.2.3]="secret"
[192.168.2.2]="secret"
)

# for ssh
ssh_keygen="/usr/bin/ssh-keygen"
ssh_key_type="rsa"
ssh_pwd=''
ssh_key_bash_dir=~/.ssh
ssh_pri_key=$ssh_key_bash_dir/id_rsa
ssh_pub_key=$ssh_key_bash_dir/id_rsa.pub
ssh_known_hosts=$ssh_key_bash_dir/known_hosts
ssh_copy_id="/usr/bin/ssh-copy-id"

DATETIME=`date "+%F %T"`

success() {
    printf "\r[ \033[00;32m$DATETIME INFO\033[0m ]%s\n" "$1"
}

warn() {
    printf "\r[\033[0;33m$DATETIME WARNING\033[0m]%s\n" "$1"
}

fail() {
    printf "\r[ \033[0;31m$DATETIME ERROR\033[0m ]%s\n" "$1"
}

usage() {
    echo "Usage: ${0##*/} {info|warn|err} MSG"
}

log() {
    if [ $# -lt 2 ]; then
        log err "Not enough arguments [$#] to log."
    fi

    __LOG_PRIO="$1"
    shift
    __LOG_MSG="$*"

    case "${__LOG_PRIO}" in
        crit) __LOG_PRIO="CRIT";;
        err) __LOG_PRIO="ERROR";;
        warn) __LOG_PRIO="WARNING";;
        info) __LOG_PRIO="INFO";;
        debug) __LOG_PRIO="DEBUG";;
    esac

    if [ "${__LOG_PRIO}" = "INFO" ]; then
        success " $__LOG_MSG"
    elif [ "${__LOG_PRIO}" = "WARNING" ]; then
        warn " $__LOG_MSG"
    elif [ "${__LOG_PRIO}" = "ERROR" ]; then
        fail " $__LOG_MSG"
    else
       usage
    fi
}

get_cipher() {
    local IP=$1

    for key in ${!IPListDict[@]}; do
        if [[ X"$IP" == X"$key" ]]; then
            PASSWORD="${IPListDict[$key]}"
        fi
    done
}

is_exist() {
    local IP=$1

    if `grep -q "$IP" ${ssh_known_hosts}`; then
        return 0
    fi

    return 1
}

del_exist_host() {
    local IP=$1

    sed -i "/$IP/d" ${ssh_known_hosts}
}

generate_ssh_key() {
   if [ ! -f ${ssh_pri_key} ]; then
       ${ssh_keygen} -t ${ssh_key_type} -P "${ssh_pwd}" -f ${ssh_pri_key} &> /dev/null
       if [ $? -eq 0 ]; then
           log info "Generated ssh key successfully."
       else
           log err "Generated ssh key failed."
       fi
   else
       echo "y" | ${ssh_keygen} -t ${ssh_key_type} -P "${ssh_pwd}" -f ${ssh_pri_key} &> /dev/null
       if [ $? -eq 0 ]; then
           log info "Generated ssh key successfully."
       else
           log err "Generated ssh key failed."
       fi
   fi
}

copy_pub_key() {
   local IP=$1

   if [ -f ${ssh_known_hosts} ]; then
       is_exist $IP
       if [ $? -eq 0 ]; then
           del_exist_host $IP
       fi
   fi
   
   get_cipher $IP
   
   expect -c <<- EOF &> /dev/null "
       spawn $ssh_copy_id -i "$ssh_pub_key" $USER_NAME@$IP
       expect {
            \"(yes/no)?\" {
                send \"yes\r\"
                expect {
                    "*assword" {
                        send \"$PASSWORD\r\"
                    }
                }
            }

            "*assword*" {
                send \"$PASSWORD\r\"
            }
            expect eof    
        }
        catch wait retVal
        exit [lindex \$retVal 3]"
EOF
       if [ $? -eq 0 ]; then
           log info "Copy the ssh pub key to $IP successfully."
       else
           log err "Copy the ssh pub key to $IP failed."
       fi
}


# main
for ip in ${!IPListDict[@]}; do
    if [[ X"$ip" == X"${LOCAL_IP}" ]]; then
        generate_ssh_key
        continue
    fi
    copy_pub_key $ip
done


本文由【waitig】发表在等英博客
本文固定链接:shell实现对多台服务器ssh免密登录
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)