天天看點

linux ntp 定時同步_linux 時間同步的2種方法

推薦第一種 !

由于硬體的原因,機器或多或少的根标準時間對不上,一個月的誤差幾秒到幾分鐘不等。對于伺服器來說時間不準,會有很多麻煩。例如,支付的時候,無法下單,遊戲無法登入等。自己用的PC就無所謂了,手動改一下就行了。

一,用ntpdate從時間伺服器更新時間

如果你的linux系統根本沒有ntpdate這個指令, 可先安裝 :

yum install ntp

安裝完了之後,你不要做什麼配置,也不需要,直接測試一下

vi /etc/ntp.conf

add below:

server 1.cn.pool.ntp.org

server 3.asia.pool.ntp.org

server 2.asia.pool.ntp.org

restart service and sync the time

[[email protected] ~]# ntpdate time.nist.gov22 Oct 21:11:43 ntpdate[5014]: adjust time server 207.200.81.113 offset -0.018788 sec

如果出去上面的内容說明,同步成功了。然後在crontab裡面加上以下内容。

*/10 * * * * ntpdate time.nist.gov #域名或IP

每隔十分鐘同步一次。推薦幾個時間伺服器。

time.nist.gov

time.nuri.net

0.asia.pool.ntp.org

1.asia.pool.ntp.org

2.asia.pool.ntp.org

3.asia.pool.ntp.org

如果出現the NTP socket is in use, exiting問題

機房中的ESX4的伺服器時間不對,ESX Server的時間準确比較重要,因為其上的VM(虛拟主機)的時間與其同步。在ESX4上使用NTP伺服器同步時間,卻遇到了“the NTP socket is in use, exiting”的問題,操作過程指令如下:

[[email protected] ~]# ntpdate time.nist.gov21 Sep 14:39:09 ntpdate[24744]: the NTP socket is in use, exiting

[[email protected]~]# service ntpd stop

Shutting down ntpd: [ OK ]

[[email protected]~]# ntpdate time.nist.gov22 Oct 21:11:43 ntpdate[5014]: adjust time server 207.200.81.113 offset -0.018788 sec

二,用ntp搭建自己的時間伺服器

上面我們是利用别人的時間伺服器來同步時間,這些時間伺服器都是比較權威的。當我們自己搭建時間伺服器就不用crontab來定時去跑。

1,安裝時間伺服器ntp

yum install ntp

2,配置ntp

[[email protected] ~]# cat /etc/ntp.conf |awk '{if($0 !~ /^$/ && $0 !~ /^#/) {print $0}}'restrictdefault ignore //預設不允許修改或者查詢ntp,并且不接收特殊封包

restrict 127.0.0.1 //給于本機所有權限

restrict 192.168.1.0 mask 255.255.255.0 notrap nomodify //給于區域網路機的機器有同步時間的權限

server time.nist.gov prefer //設定時間伺服器,加prefer表示優先

server 0.asia.pool.ntp.org

server1.asia.pool.ntp.org

server2.asia.pool.ntp.org

server127.127.1.0# local clock

fudge127.127.1.0 stratum 10driftfile/var/lib/ntp/drift

keys/etc/ntp/keys

3,啟動 ntp

[[email protected] ~]# /etc/init.d/ntpd start

4,檢視并測試

[[email protected] ~]# netstat -upnl |grep ntpd //檢視時程

[[email protected]~]# ntpq -pn //檢視同步的伺服器IP

remote refid st t when poll reach delay offset jitter==============================================================================

50.77.217.185 .INIT. 16 u - 64 0 0.000 0.000 0.000

202.90.158.4 .INIT. 16 u - 64 0 0.000 0.000 0.000

202.71.100.89 .INIT. 16 u - 64 0 0.000 0.000 0.000

202.134.1.10 .INIT. 16 u - 64 0 0.000 0.000 0.000

*127.127.1.0 .LOCL. 10 l 18 64 377 0.000 0.000 0.001[[email protected]~]# ntpstat //同步的結果

synchronised to local net at stratum 11time correct to within12ms

polling server every512 s

remote:即NTP主機的IP或主機名稱。注意最左邊的符号,如果由“+”則代表目前正在作用鐘的上層NTP,如果是“*”則表示也有連上線,不過是作為次要聯機的NTP主機。

refid:參考的上一層NTP主機的位址

st:即stratum階層

when:幾秒前曾做過時間同步更新的操作

poll:下次更新在幾秒之後

reach:已經向上層NTP伺服器要求更新的次數

delay:網絡傳輸過程鐘延遲的時間

offset:時間補償的結果

jitter:Linux系統時間與BIOS硬體時間的差異時間

推薦第一種方法,雖然搭建個時間伺服器,還是比較簡單的,但是我覺得沒有這個必要。如果用别人的時間伺服器,每隔10分鐘同步一次,可以精确到毫秒。