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*