Shell 同步时间脚本

  Linux系统同步时间脚本

  Linux操作系统,如果时间和网络时间差距太大的话。可能会导致程序,进程启动不了。所以linux系统时间同步显得尤为重要,本文在借鉴网上众多资料后,以centos_6.X系统为例,整理同步时间的脚步,如有不合理的地方,敬请说明。

一、创建脚本目录

 

[root@shell ~]# mkdir /usr/local/scripts

 

二、脚本内容

 

[root@shell ~]# cat /usr/local/scripts/Sync_NTP.sh

 

cat /root/ntp.sh 

#!/bin/bash

#######################################################
# Function: Inspection Time
# Author: davie
# Date: 2017-12-02
# Version: 1.0
# QQ: 178570692
# Script name: /usr/local/scripts/Sync_NTP.sh
# http://www.cnblogs.com/bjx2020/
#######################################################
# List of NTP's servers


ntp_cmd="/usr/sbin/ntpdate"
if [ ! -f "${ntp_cmd}" ]; then
echo "/usr/sbin/ntpdate does not exists!"
yum -y install ntp* >/dev/null
fi

#NTP服务器数组列表
ntpServer=(
[0]=0.cn.pool.ntp.org
[1]=1.cn.pool.ntp.org
[2]=2.cn.pool.ntp.org
[3]=3.cn.pool.ntp.org
)
#校验#
serverNum=`echo ${#ntpServer[*]}`
NUM=0
for ((i=0; i<=$serverNum; i++)); do
echo -n "正在和NTP服务器:${ntpServer[$NUM]}校验中..."
/usr/sbin/ntpdate ${ntpServer[$NUM]} >> /dev/null 2>&1
if [ $? -eq 0 ]; then
echo -e "\e[1;32m\t[成功]\e[0m"
echo -e "\e[1;32m同步成功,退出......\e[0m"
break
else
echo -e "\e[1;31m\t[失败]\e[0m"
echo -e "\e[1;31m继续同步下一个!!!!!\e[0m"
let NUM++
fi
sleep 2
done
# chmod +x /root/ntp.sh

# sh /root/ntp.sh

 

 

 

三、执行脚本测试

[root@shell ~]# mkdir /usr/local/scripts
[root@shell ~]# vim /usr/local/scripts/Sync_NTP.sh
[root@shell ~]# chmod +x /usr/local/scripts/Sync_NTP.sh
[root@shell ~]# sh /usr/local/scripts/Sync_NTP.sh
Sync time with the NTP server: 1.cn.pool.ntp.org Checking... [ success ]
[root@shell ~]# 

 

演示一个不能同步某个服务器时间的例子。故意修改第一个NTP服务器的网址即可。

这里将:[0]=1.cn.pool.ntp.org

修改为: [0]=xx1.cn.pool.ntp.org

再次执行脚本:

[root@shell ~]# sh /usr/local/scripts/Sync_NTP.sh
Sync time with the NTP server: xx1.cn.pool.ntp.org Checking... [ fail ]
Continue to sync the next!!!
Sync time with the NTP server: 2.cn.pool.ntp.org Checking... [ success ]
[root@shell ~]#

 

四、将其加入计划任务中

每隔一小时同步一次。前期时间同步一致后,建议将其间隔调整大一点。

[root@shell ~]# crontab -l
01 */1 * * * /usr/local/scripts/Sync_NTP.sh >/dev/null
[root@shell ~]# 

 

五、说明

有些系统在安装时,没有ntp相关命令,就需要用yum安装。

注意:系统本身需要同步外部服务器时间,所以需要连接外网。对于内网服务器有安全要求限制的话,只需要将ntp服务器网址修改成对应的内网时间服务器即可。

[root@shell ~]# /usr/sbin/ntpdate 1.cn.pool.ntp.org
-bash: /usr/sbin/ntpdate: No such file or directory
[root@shell ~]# yum -y install ntpd*

 

posted @ 2017-12-02 20:35  davie2020  阅读(3899)  评论(0编辑  收藏  举报