导航

shell脚本配置ssh免密登陆

Posted on 2018-07-03 12:38  张鑫的园子  阅读(905)  评论(0编辑  收藏  举报

通过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\r"
        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\r";exp_continue }
                        "*assword:" { send "$PASSWD\r" }
        }
        sleep 1
        send "ssh-keygen -t rsa -b 2048 -N '' -f $HOME/.ssh/id_rsa\r"
        expect  {
                        "(y/n)" { send "y\r" }
        }
        sleep 1 
        send "exit\r"
        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\r";exp_continue }
                        "*assword:" { send "$PASSWD\r" }
        }
        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\r";exp_continue }
                        "*assword:" { send "$PASSWD\r" }
        }
        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 "\033[031;1m$@\033[0m"; }
green_echo ()    { echo -e "\033[032;1m$@\033[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

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