linux 時間同步的2種方法


轉載自: http://blog.51yip.com/server/1474.html

由於硬件的原因,機器或多或少的根標准時間對不上,一個月的誤差幾秒到幾分鍾不等。對於服務器來說時間不准,會有很多麻煩。例如,支付的時候,無法下單,游戲無法登錄等。自己用的PC就無所謂了,手動改一下就行了。

 

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

如果你的linux系統根本沒有ntpdate這個命令

  1. 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

  1. [root@localhost ~]# ntpdate time.nist.gov  
  2. 22 Oct 21:11:43 ntpdate[5014]: adjust time server 207.200.81.113 offset -0.018788 sec  

如果出去上面的內容說明,同步成功了。然后在crontab里面加上以下內容。

  1. */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

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

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

1,安裝時間服務器ntp

  1. yum install ntp  

2,配置ntp

  1. [root@localhost ~]# cat /etc/ntp.conf |awk '{if($0 !~ /^$/ && $0 !~ /^#/) {print $0}}'  
  2. restrict default ignore   //默認不允許修改或者查詢ntp,並且不接收特殊封包  
  3. restrict 127.0.0.1        //給於本機所有權限  
  4. restrict 192.168.1.0 mask 255.255.255.0 notrap nomodify  //給於局域網機的機器有同步時間的權限  
  5. server time.nist.gov prefer      //設置時間服務器,加prefer表示優先  
  6. server 0.asia.pool.ntp.org  
  7. server 1.asia.pool.ntp.org  
  8. server 2.asia.pool.ntp.org  
  9. server  127.127.1.0     # local clock  
  10. fudge   127.127.1.0 stratum 10  
  11. driftfile /var/lib/ntp/drift  
  12. keys /etc/ntp/keys  

3,啟動 ntp

  1. [root@localhost ~]# /etc/init.d/ntpd start  

4,查看並測試

  1. [root@localhost ~]# netstat -upnl |grep ntpd   //查看時程  
  2.   
  3. [root@localhost ~]# ntpq -pn    //查看同步的服務器IP  
  4.  remote           refid      st t when poll reach   delay   offset  jitter  
  5. ==============================================================================  
  6.  50.77.217.185   .INIT.          16 u    -   64    0    0.000    0.000   0.000  
  7.  202.90.158.4    .INIT.          16 u    -   64    0    0.000    0.000   0.000  
  8.  202.71.100.89   .INIT.          16 u    -   64    0    0.000    0.000   0.000  
  9.  202.134.1.10    .INIT.          16 u    -   64    0    0.000    0.000   0.000  
  10. *127.127.1.0     .LOCL.          10 l   18   64  377    0.000    0.000   0.001  
  11.   
  12. [root@localhost ~]# ntpstat   //同步的結果  
  13. synchronised to local net at stratum 11  
  14.  time correct to within 12 ms  
  15.  polling server every 512 s  

remote:即NTP主機的IP或主機名稱。注意最左邊的符號,如果由“+”則代表目前正在作用鍾的上層NTP,如果是“*”則表示也有連上線,不過是作為次要聯機的NTP主機。
refid:參考的上一層NTP主機的地址
st:即stratum階層
when:幾秒前曾做過時間同步更新的操作
poll:下次更新在幾秒之后
reach:已經向上層NTP服務器要求更新的次數
delay:網絡傳輸過程鍾延遲的時間
offset:時間補償的結果
jitter:Linux系統時間與BIOS硬件時間的差異時間

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM