Linux集群自动化搭建(生成密钥对+分发公钥+远程批量执行脚本)
Linux集群自动化搭建(生成密钥对+分发公钥+远程批量执行脚本)本文将介绍如何通过ssh + expect + scp实现服务器集群的自动化搭建。第一步,服务器准备这里使用docker模拟几台服务器,分别命名为node2,node3,node4(使用镜像chenqionghe/Ubuntu,密码统一为88888888),生产环境为ip或hostdocker run -d --name node2 -p 2223:22 chenqionghe/ubuntu
docker run -d --name node3 -p 2224:22 chenqionghe/ubuntu
docker run -d --name node4 -p 2225:22 chenqionghe/ubuntu还得有一台主控制服务器node1,负责操作所有的服务器节点docker run -d --name node1 -p 2222:22 \
--link node2:node2 \
--link node3:node3 \
--link node4:node4 \
chenqionghe/ubuntu初始化完成后进入node1节点ssh root@127.0.0.1 -p 2222安装必须软件apt-get install expect -y创建存放脚本的目录~/envmkdir -p ~/env && cd ~/env这里先模拟一个简单的安装包scripts/install.sh,安装vim命令mkdir scripts
cat > scripts/install.sh <<EOF
#!/bin/bash bash
apt-get install vim -y
EOF创建机器列表配置文件,vim nodes.txtnode2
node3
node4第二步 编写自动化脚本
1.无交互ssh-keygen生成密钥对脚本,vimssh-keygen.exp#!/usr/bin/expect
#set enter "\n"
spawn ssh-keygen
expect {
"*(/root/.ssh/id_rsa)" {send"\r";exp_continue}
"*(empty for no passphrase)" {send"\r";exp_continue}
"*again" {send "\r"}
}
expect eof2.无交互分发公钥脚本,vim send-sshkey.exp#!/usr/bin/expect
if { $argc != 2 } {
send_user "usage: expect send-sshkey.exp file host\n"
exit
}
#define var
set file
set host
set password "88888888"
spawn ssh-copy-id -i $file -p 22 root@$host
expect {
"yes/no" {send"yes\r";exp_continue}
"*password" {send "$password\r"}
}
expect eof 3.远程批量执行ssh脚本, vim mssh.sh#!/bin/bash
Port=22
if [ $# -lt 1 ];then
echo "Usage: `basename $0` command"
exit
fi
echo $@
for v in `cat nodes.txt`
do
ssh -t -p ${Port} root@${v} $@
if [ $? -eq 0 ];then
echo "执行成功:$v"
else
echo "执行失败:$v"
fi
done4.自动化部署脚本,vim auto-deploy.sh#!/usr/bin/env bash
#机器列表
HostList=`cat nodes.txt`
#端口号
Port=22
# 1.无交互生成密钥对
if [ ! -f ~/.ssh/id_rsa.pub ];then
expect ssh-keygen.exp
fi
# 2.无交互分发公密钥
for v in ${HostList}
do
expect send-sshkey.exp ~/.ssh/id_rsa.pub ${v}
if [ $? -eq 0 ];then
echo "公钥-发送成功:$v"
else
echo "公钥-发送失败:$v"
fi
done
# 3.分发脚本文件(安装软件包)
for v in ${HostList}
do
scp -P ${Port} -rp ~/env/scripts root@${v}:~
if [ $? -eq 0 ];then
echo "scripts-发送成功:$v"
else
echo "scripts-发送失败:$v"
fi
done
# 4.使用脚本文件安装
for v in ${HostList}
do
ssh -t -p ${Port} root@${v} /bin/bash ~/scripts/install.sh
done到这里所有的文件已经创建完成,整个env目录结构如下├── auto-deploy.sh
├── mssh.sh
├── nodes.txt
├── scripts
│└── install.sh
├── send-sshkey.exp
└── ssh-keygen.exp第三步 执行自动化脚本查看效果sh auto-deploy.sh执行成功结果spawn ssh-keygen
...
公钥-发送成功:node2
...
公钥-发送成功:node3
...
公钥-发送成功:node4
install.sh 100% 40 41.4KB/s 00:00
scripts-发送成功:node2
install.sh 100% 40 45.0KB/s 00:00
scripts-发送成功:node3
install.sh 100% 40 39.9KB/s 00:00
scripts-发送成功:node4
...
Connection to node4 closed.出现上面的结果代表3个node节点已经初始化完成,拷贝公钥+安装软件成功!我们再来执行一下远程命令脚本,查看所有服务器系统类型sh mssh.sh "cat /etc/os-release|head -n 1"执行结果如下cat /etc/os-release|head -n 1
NAME="Ubuntu"
Connection to node2 closed.
执行成功:node2
NAME="Ubuntu"
Connection to node3 closed.
执行成功:node3
NAME="Ubuntu"
Connection to node4 closed.
执行成功:node4这样就实现了自动化创建密钥对+分发公钥+所有服务器软件环境安装+批量远程执行脚本mssh.sh
感谢楼主分享!
页:
[1]