1. 程式人生 > >Linux 時間同步腳本

Linux 時間同步腳本

ntp ron bash 註意事項 ntp服務 加密 stat ash ive

參考資料:
http://www.cnblogs.com/liushui-sky/p/9203657.html(博客中perfer應該為prefer)

https://www.jianshu.com/p/80ab71d50872

https://www.cnblogs.com/quchunhui/p/7658853.html

https://www.cnblogs.com/kerrycode/archive/2015/08/20/4744804.html

man -k ntp
man ntp.config

ntp服務器地址:
http://www.ntp.org.cn

註意事項:
1、防火墻放行123端口
2、如果主從服務時間超過1000秒則不再進行同步了,這時候要手動同步,

Centos6腳本(使用ntp/ntpdate):

1、服務器端配置

#!/bin/bash
#1、不用判斷,直接安裝,有的話就不會安裝,沒的話也就安裝上了。

yum -q -y ntp ntpdate &>/dev/null

#2、配置ntp服務

sed -i ‘s/^server/#server/g‘  /etc/ntp.conf
sed -i ‘s/^restrict -6/#restrict -6/g‘  /etc/ntp.conf
cat >> /etc/ntp.conf <<eof
#start custom config
#添加同步的服務器地址
server cn.ntp.org.cn prefer
#權限控制
restrict  192.168.0.0 mask 255.255.0.0 nomodify notrap
#end
eof

#3、設置ntp,進行硬件時鐘同步

echo "SYNC_HWCLOCK=yes" >>/etc/sysconfig/ntpd

#4、首次客戶端和服務器端時間超過1000秒,就不會去同步,所以先ntpdate先同步下時間。

ntpdate cn.ntp.org.cn &>/dev/null && hwclock -w 

#5、放行防火墻規則

iptables -I INPUT -p udp --dport 123 -j ACCEPT
iptables-save >/etc/sysconfig/iptables

#6、啟動服務,添加開機自啟

service ntpd start 
chkconfig ntpd on 

以上,過5分鐘ntpstat查看下是否同步了,如下圖

技術分享圖片

2、客戶端配置

和服務器一樣,只不過server地址改成ntp服務器地址即可。

Centos7腳本(使用chrony):

ntp.conf
1、配置同步源
2、配置權限
3、配置工作模式和加密模式。

Linux 時間同步腳本