内网集群准同步shell脚本

在公司的内网中配置集群同步,可能是代理问题,ntpd和chrony都没有用,所以只好写shell脚本解决

前提条件集群中各台机器已经配置好了免密登录

一、免密登录配置

1. 用 root 用户登录。每台服务器都生成公钥,再合并到 authorized_keys。
2. CentOS 默认没有启动 ssh 无密登录 ,每台服务器都要配置 /etc/ssh/sshd_config。
vi /etc/ssh/sshd_config 修改
UseDNS no
PubkeyAuthentication yes
3. 每台服务器下都输入命令 ssh-keygen -t rsa,生成 key,一律不输入密码,直接回车,/root 就会生成 .ssh 文件夹。
4. 在 Master 服务器下,合并公钥到 authorized_keys 文件,进入 /root/.ssh 目录,通过 SSH 命令合并.
cat id_rsa.pub>> authorized_keys
ssh root@bigdata02 cat ~/.ssh/id_rsa.pub>> authorized_keys
ssh root@bigdata03 cat ~/.ssh/id_rsa.pub>> authorized_keys
5. 把 Master 服务器的 authorized_keys、known_hosts 复制到 Slave 服务器的 `/root/.ssh 目录
scp authorized_keys root@bigdata02:/root/.ssh/
scp authorized_keys root@bigdata03:/root/.ssh/
scp known_hosts root@bigdata02:/root/.ssh/
scp known_hosts root@bigdata03:/root/.ssh/

二、准同步脚本timer.sh,在master主机的时间上加了5秒钟,因为执行脚本有点延迟,将准同步的范围缩小

#!/usr/bin/env bash

#hosts array

hosts=("bigdata02" "bigdata03" "bigdata04" "bigdata05")

#localhost current time 

date1=`date "+%Y/%m/%d %H:%M:%S"`
date2=`date -d "$date1 5 second" +"%Y/%m/%d %H:%M:%S"`

echo "Now the time is $date1"

#loop host to set time

for hostname in ${hosts[*]}

do

    theDay=`date -d "$date2" +"%Y-%m-%d"`
    theTime=`date -d "$date2" +"%H:%M:%S"`
    
    echo $hostname

    ssh -t $hostname bash -c "'date -s '$theDay' &&hwclock --systohc'"
    ssh -t $hostname bash -c "'date -s '$theTime' &&hwclock --systohc'"

done

三、在master上设置定时任务

配置centos7定时任务 每小时执行一次
开启定时任务
systemctl start crond
systemctl enable crond.service
编辑当前crontab,输入 crontab -e
* */1 * * * sh /home/timer.sh
原文地址:https://www.cnblogs.com/schoolbag/p/9579350.html