天天看點

Linux時間同步

在我們的項目中,需要同步Linux伺服器的時間,于是用到了ntpdate指令

1.使用crontab -l指令檢視定時服務

[root@MyCloudServer xxx]# crontab -l

0,10,20,30,40,50 * * * * ntpdate time.windows.com &>/xxx/ntpdate.log

2.看起來好像沒有問題啊,vim /var/spool/mail/root(定時服務日志會存放在該檔案中)檢視定時服務日志,發現有如下資訊

/bin/sh: ntpdate: command not found

說明定時服務在/bin/sh目錄中去找ntpdate指令,并且沒有找到

3.使用whereis ntpdate指令看看該指令在什麼目錄下

[root@MyCloudServer cron]# whereis ntpdate

ntpdate: /usr/sbin/ntpdate /usr/share/man/man8/ntpdate.8.gz

問題找到了,在定時服務中,ntpdate指令要使用全路徑

4.使用crontab -e指令修改一下,加上ntpdate指令的目錄

0,10,20,30,40,50 * * * * /usr/sbin/ntpdate time.windows.com &>/xxx/ntpdate.log

然而儲存後,等到整數分鐘後,在日志中沒有發現該指令執行,為什麼呢,猜想如下

a.以上指令格式錯誤,時間格式錯誤

b.cron自動服務沒有執行

通過網上查找時間的指令格式,發現

0,10,20,30,40,50 * * * *

并沒有錯誤,而手動執行

/usr/sbin/ntpdate time.windows.com &>/xxx/ntpdate.log

也成功執行,那麼就看看b是否存在問題

5.執行ps -ef | grep cron,檢視時間服務程序是否存在

[root@MyCloudServer xxx]# ps -ef | grep cron

root     26157 22992  0 10:04 pts/3    00:00:00 grep cron

發現沒有cron執行程序

6.執行service crond status檢視服務狀态

[root@MyCloudServer xxx]# service crond status

crond is stopped

竟然服務沒有啟動,好吧

7.啟動程序,并且檢視狀态

[root@MyCloudServer xxx]# service crond start

Starting crond:                                            [  OK  ]

crond (pid  26291) is running...

root     26291     1  0 10:06 ?        00:00:00 crond

root     26302 22992  0 10:06 pts/3    00:00:00 grep cron

8.服務啟動了,通過vim /etc/rc.d/rc.local指令添加以下語句設定為開機啟動

/sbin/service crond start

注意也加上了/sbin目錄

9.最後再看看ntpdate.log中有沒有執行日志

[root@MyCloudServer xxx]# cat ntpdate.log

29 Dec 11:10:16 ntpdate[29960]: no server suitable for synchronization found

發現伺服器沒有找到對應的服務同步,那麼猜想應該是time.windows.com伺服器在本台伺服器上沒有擷取成功,由于我們用的是香港的雲伺服器,那麼換一個香港認可的位址試試

0,10,20,30,40,50 * * * * /usr/sbin/ntpdate stdtime.gov.hk &>/xxx/ntpdate.log

然後等到整時分鐘的時候再次檢視一下

29 Dec 11:20:01 ntpdate[30580]: adjust time server 118.143.17.82 offset 0.015206 sec

可以看到執行成功了

總結:通過以上問題調查,發現無論什麼時候經驗主義并不可靠,小小的一個問題都可能引發很多原因。

繼續閱讀