批量部署免密登錄及批量修改主機名ssh

注):主機需安裝pssh、expect相關命令;
一、由中心主機生成公鑰並批量傳輸至各節點
中心主機以root執行ssh-keygen -t rsa
在/root/.ssh/下生成id_rsa(私鑰); id_rsa.pub(公鑰);
cat /root/.ssh/id_rsa.pub > /tmp/authorized_keys //備份並授權chmod 600
通過shell傳輸公鑰至各節點(scp.sh&info.txt):
//cat scp.sh (scp shell)

#!/bin/bash
if [ $# -ne 1 ] ;then
    echo "need server  info file!"
        exit 1
fi
        while read line
        do
        arr=(${line//,/ })
        ip=${arr[0]}
        port=${arr[1]}
        user=${arr[2]}
        pass=${arr[3]}
        path=${arr[4]}
            expect -c "
            spawn /usr/bin/scp -pP$port /tmp/authorized_keys  $user@$ip:$path
            expect  {
                \"*(yes/no)?\" 
                    {
                        exp_send \"yes\r\";exp_continue
                        expect \"*password:\" { send \"${pass}\r\" }
                    }               
                \"*password:\"
                    {
                        send \"${pass}\r\"
                    }
                }
            expect eof 
            "
        done <$1

//cat info.txt (接收公鑰節點信息;格式:IP,端口,用戶名,密碼,用戶家目錄/.ssh)
10.1.1.1,22,root,123456,/root/.ssh/
10.1.1.2,22,root,123456,/root/.ssh/
……
//批量傳輸公鑰 /bin/bash scp.sh info.txt
//驗證無密碼登錄ssh -P22 [email protected]
========>>
二、批量修改主機名
// cat host.sh (修改主機名shell)

#!/bin/bash
ip=$(ifconfig eth0 |awk -F '[ :]+' 'NR==2 {print $4}')
hos_t=$(cat /tmp/host_ip.txt |awk -F ',' '/'$ip'/{print $1}')
sed -i "s#\(HOSTNAME=\).*#\1${hos_t}#g" /etc/sysconfig/network

// cat host_ip.txt (主機名與IP信息;格式:主機名,IP)
Centos_001,10.1.1.1
Centos_002,10.1.1.2
……
//cat pssh.txt (pssh遠程主機列表;格式:用戶名@IP:端口)
[email protected]:22
[email protected]:22
……
//中心主機傳輸並執行host.sh & host_ip.txt
//執行 pscp -h pssh.txt host.sh host_ip.txt /tmp/
//執行 pssh -h pssh.txt “/bin/bash /tmp/host.sh”
驗證:略

                                            ^_^能力有限,歡迎指正~
                                                    2018-08-31
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章