shell脚本配置ssh免密登陆

通过shell脚本配置免密登陆,分为两个脚本,一个是配置文件config.env,一个是正式脚本sshkey.sh。

# config.env
export HOST_USER=(root) export PASSWD=(a) export SSH_HOST=(192.168.165.15 192.168.165.16 192.168.165.165)

以上congfig.env文件中,SSH_HOST参数可配置多个IP,可配置不同的用户

sshkey.sh脚本内容大致如下:

  1. 在本地用rsa加密方式生成对应的密钥,并将公钥写入到authorized_keys文件中;
  2. 遍历多台远程服务器,登陆远程服务器生成密钥,并将公钥文件考本到本机,写入本机的authorized_Keys文件中;
  3. 遍历多台远程服务器,将本地的authorized_Keys文件分别分发到各台服务器上。
#!/bin/bash
# sshkey.sh
source config.env

createLocalKey () {
        /usr/bin/expect <<_oo_
        spawn ssh-keygen -t rsa -b 2048 -N "" -f $HOME/.ssh/id_rsa
        expect "Overwrite"
        send "y
"
        expect eof
_oo_
        cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
}

createRemoteKey () {
        /usr/bin/expect <<_oo_
        spawn ssh $HOST_USER@$ip
        expect {
                        "yes/no" { send "yes
";exp_continue }
                        "*assword:" { send "$PASSWD
" }
        }
        sleep 1
        send "ssh-keygen -t rsa -b 2048 -N '' -f $HOME/.ssh/id_rsa
"
        expect  {
                        "(y/n)" { send "y
" }
        }
        sleep 1 
        send "exit
"
        expect eof
_oo_

        /usr/bin/expect <<_oo_
        spawn scp $HOST_USER@$ip:$HOME/.ssh/id_rsa.pub /tmp/id_rsa$ip.pub
        expect {
                        "yes/no" { send "yes
";exp_continue }
                        "*assword:" { send "$PASSWD
" }
        }
        expect eof
_oo_

        cat /tmp/id_rsa$ip.pub >> $HOME/.ssh/authorized_keys
        rm -rf /tmp/id_rsa$ip.pub
}

copyToRemote () {
        /usr/bin/expect <<_oo_
        spawn scp $HOME/.ssh/authorized_keys $HOST_USER@$ip:$HOME/.ssh/authorized_keys
        expect {
                        "yes/no" { send "yes
";exp_continue }
                        "*assword:" { send "$PASSWD
" }
        }
        expect eof
_oo_
}

pullPubKey () {
        for ip in ${MHA_HOST[@]};do
                if [ $ip == `ifconfig eth0|grep -oP '(?<=inet addr:)S+'` ];then
                        echo "It's local host"
                else
                        createRemoteKey
                fi
        done
}

pushAuthorizedKeys () {
        for ip in ${MHA_HOST[@]};do
                if [ $ip == `ifconfig eth0|grep -oP '(?<=inet addr:)S+'` ];then
                        echo "It's local host"
                else
                        copyToRemote
                fi
        done
}

taskMain () {
        createLocalKey 
        pullPubKey
        pushAuthorizedKeys
}

red_echo ()      { echo -e "33[031;1m$@33[0m"; }
green_echo ()    { echo -e "33[032;1m$@33[0m"; }

taskMain; rc=$?
if [ $rc -ne 0 ] ;then
   echo "$(red_echo Config ssh without password failed!)"
else
   echo "$(green_echo Config ssh without password success!)"
fi
exit $rc

如有更好的解决方案,望留言指出,谢谢

原文地址:https://www.cnblogs.com/zx3212/p/9257996.html