1. 程式人生 > >shell腳本配置ssh免密登陸

shell腳本配置ssh免密登陸

add home copy The authorize code 本地 ont 參數

通過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 () { [ "$HASTTY" == 0 ] && echo "$@" || echo -e "\033[031;1m$@\033[0m"; } green_echo () { [ "$HASTTY" == 0 ] && 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

如有更好的解決方案,望留言指出,謝謝

shell腳本配置ssh免密登陸