批量部署免密登录及批量修改主机名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

你可能感兴趣的:(shell)