一个 shell 脚本搞定 服务器集群间 免密登录

我努力成为 一名 学者。

写这个脚本之前,自己对于shell脚本,涉及很少。 如果不当之处,还望不吝指教。

 

#! /bin/bash

############################ 生成 SSH 公钥密钥 ########################## 

expect << EOF 
spawn ssh-keygen -t rsa 

expect "Enter file in which to save the key (/root/.ssh/id_rsa):" { send "\r" }
expect "Enter passphrase (empty for no passphrase):" { send "\r" }
expect "Enter same passphrase again:" {send "\r"}

expect eof
EOF

############################ 配置 集群节点免密登陆 ###################### 

## 获取本机 IP 地址
IP=`ifconfig eth0 | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2 }' | tr -d addr:]`
## 打印
echo $IP  


## 集群地址 密码    我在这里使用 主机名,并已配置 hosts。 
servers="master slave1 slave2"
password="123456"
## 获取当前主机 主机名
hostname=`hostname`
startname="master"


##  配置免密登录
auto_copy(){
expect << eof
    spawn ssh-copy-id $1
    expect {
        "(yes/no)" { send "yes\r"; exp_continue; }
        "*assword:" { send $2\r }
    }
    expect eof
eof
}

##  复制 脚本 到集群节点
copy_target_host(){
expect << eof
    spawn scp /root/ssh-deploye.sh root@$1:/root
    expect {
	"(yes/no)" { send "yes\r"; exp_continue; }
        "*assword:" {send $2\r }
    }
    expect eof
eof
}


## 执行 部署脚本
execute_script(){
expect << eof 
    spawn ssh root@$1 sh /root/ssh-deploye.sh
    expect {
        "(yes/no)" { send "yes\r"; exp_continue; }
        "*assword:" {send $2\r }
    }
    expect eof 
eof
}


for server in $servers
do	
    if [ $hostname = $startname ]
    then 
        echo "脚本起始执行节点  ${hostname},拷贝脚本 至 其余集群节点。 "
	if [ $server == $startname ]
	then 
            echo "自己不拷贝"
        else 
  	    echo "拷贝节点 $server"
            copy_target_host $server $password
            execute_script $server $password
        fi
    else
        echo "集群节点 ${hostname} "
    fi
    
    # 执行部署脚本
    auto_copy $server $password
done

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值