简介

一般企业由于安全或者出口带宽等各方面的原因,内网主机是无法直接联通外网,我们这里总结一个教程可以让内网无法上网的机器同步本机时间,而本机可以通过公网沟通不公网的ntp源。

时间服务器的解释以及重要性

网络时间协议NTP(Network Time Protocol)是由于互联网中时间同步的标准互联网协议。NTP的用途是把计算机的时间同步到某些时间标准。目前采用的时间标准是世界协调时间UTC( Universal Time Coordinated )

在互联网上进行时间同步具有重要意义。随着互联网的发展和延申到社会的各个方面,在其他的领域对时间同步也提出了多种要求,例如各种实时的网上交易 、通信网络的时间配置、网络安全性设计、分布性的网络计算和处理、交通航班航路管理以及数据库文件管理和呼叫记录等多种涉及时间戳的应用,都需要精确、可靠和公认的时间。如果系统内某个服务器的时间有误差会造成交互失败有歧义,严重的将导致交易失败。由此可以看出NTP服务器的存在是不容置疑的。

准备

操作系统:Centos7.4

ntpd服务器:192.168.43.253

客户端服务器:192.168.43.31

1
2
cat /etc/redhat-release #查看服务器、客户端操作系统版本
rpm -qa | grep ntp #查看服务器是否安装ntp,系统默认安装ntpdate

解决方案

1.在server端安装ntpd服务端并关闭防火墙或者放通防火墙的端口

1
2
3
4
yum install -y ntp
systemctl stop firewalld
firewall-cmd --permanent --add-port=123/udp
firewall-cmd --permanent --add-port=123/tcp

2.编辑/etc/ntp.conf并更改文件内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
vim /et	ntp.conf
### 修改以下文件内容
restrict 127.0.0.1
restrict 192.168.0.1 mask 255.255.255.240 nomodify notrap
restrict 192.168.43.0 mask 255.255.255.0 nomodify notrap
restrict 172.16.252.0 mask 255.255.255.0 nomodify notrap
#允许那些网段或者IP同步,不做限制则0.0.0.0 mask 0.0.0.0.需要注意的是4.2版本的ntpd的restrict参数不要加notrust否则客户端会同步不了。
server ntp.aliyun.com prefer
#server自身和谁同步。我这里用的是阿里云的。
server 127.127.1.0
fudge 127.127.1.0 stratum 5
#外部时间服务器不可用时,以本地时间作为时间服务
#server 0.centos.pool.ntp.org iburst

#server 1.centos.pool.ntp.org iburst

#server 2.centos.pool.ntp.org iburst

#server 3.centos.pool.ntp.org iburst
#注释掉网络服务器

3.配置完毕启动服务(设置开机自启)

1
2
3
4
systemctl start ntpd #开启服务
systemctl status ntpd #查看服务状态
查看服务是否启动:netstat -tunlp |grep ntp ;ntp默认监听于UDP的123端口
systemctl enable ntpd #设置为开机自启

4.服务端状态没有问题,去Client同步下测试

1
2
3
4
ntpdate 192.168.43.253

26 Jan 22:19:43 ntpdate[3156]: adjust time server 192.168.100.110 offset -0.001781 sec
出现上面这个没毛病,兄弟完成

5.客户端配置定时任务同步此服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@ansible named]#vim /usr/bin/ntpsync.sh

#!/bin/bash

/usr/sbin/ntpdate 192.168.113.159

#同步系统时间到硬件时间

/sbin/hwclock –w

[root@ansible named]#crontab -e

#sync time with ntpserver at 12:00

0 12 * * * /usr/bin/ntpsync.sh
1
2
3
4
5
6
7
命令讲解
手动直接输入服务器IP
ntpdate 192.168.43.253
查看本地网络时间同步状态
ntpstat
查看服务器同步状态
ntpq -p