日期 时间设置

在Linux下,默认情况下,系统时间和硬件时间,并不会自动同步。在Linux运行过程中,系统时间和硬件时间以异步的方式运行,互不干扰。硬件时间的运行,是靠Bios电池来维持,而系统时间,是用CPU tick来维持的。

在系统开机的时候,会自动从Bios中取得硬件时间,设置为系统时间。

date -s "2030/5/14 23:25:56" 修改日期 时间 (不是永久的)

修改时间:
date  -s  "2025/04/11  01:05:30"
Fri Apr 11 01:05:30 CST 2025

hwclock --systohc
# 将系统时间同步到硬件,防止系统重启后时间被还原。 sys(系统时间)to(写到)hc(Hard Clock)

同步时间:
yum -y install ntp
hwclock --systohc
crontab -l
12 * * * * /usr/sbin/ntpdate ntp1.aliyun.com


补充:
date +%F
2025-04-11

date +%Y
2025

date +%m
04

date +%d
11

date +%Y-%m-%d
2025-04-11

date +%H:%M:%S
01:05:49

date +%H
01

date +%M
05

date +%S
58

时区设置

查看时区
timedatectl
      Local time: Fri 2025-04-11 01:06:34 CST
  Universal time: Thu 2025-04-10 17:06:34 UTC
        RTC time: Thu 2025-04-10 17:06:34
       Time zone: Asia/Shanghai (CST, +0800)
     NTP enabled: no
NTP synchronized: no
 RTC in local TZ: no
      DST active: n/a


修改时区
timedatectl set-timezone Asia/Shanghai

ntpd服务

配置文件

配置文件位置: /etc/ntp.conf

在 NTP Server 的设定上面,其实最好不要对 Internet 无限制的开放,尽量仅提供您自己内部的 Client 端联机进行网络校时就好。此外, NTP Server 总也是需要网络上面较为准确的主机来自行更新自己的时间,所以在我们的 NTP Server 上面也要找一部最靠近自己的 Time Server 来进行自我校正。事实上, NTP 这个服务也是Server/Client 的一种模式。

cat /etc/ntp.conf 
# For more information about this file, see the man pages
# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).
1. 为了解决更新时间封包的传送延迟动作,所以可以使用driftfile来规定我们的主机在与 Time Server 沟通时所花费的时间,可以记录在driftfile 后面接的文件内
driftfile /var/lib/ntp/drift


# 2. 关于权限设定部分
# 权限的设定主要以 restrict 这个参数来设定,主要的语法为:
# restrict IP mask netmask_IP parameter
# 其中 IP 可以是软件地址,也可以是 default ,default 就类似 0.0.0.0
# 至于paramter则有:
#  ignore :关闭所有的 NTP 联机服务
#  nomodify:表示 Client 端不能更改 Server 端的时间参数,不过,Client 端仍然可以透过 Server 端来进行网络校时。
#  notrust:该 Client 除非通过认证,否则该 Client 来源将被视为不信任网域
#  noquery:不提供 Client 端的时间查询
#  notrap:不提供trap这个远程事件登入
#  如果paramter完全没有设定,那就表示该 IP (或网域)“没有任何限制”


# Permit time synchronization with our time source, but do not
# permit the source to query or modify the service on this system.
restrict default nomodify notrap nopeer noquery

# Permit all access over the loopback interface.  This could
# be tightened as well, but to do so would effect some of
# the administrative functions.
restrict 127.0.0.1  #不可改变回环地址
restrict ::1   #不可改变回环地址
restrict 100.100.137.0 mask 255.255.255.0 nomodify
# 在100.100.137.0/24网段内的服务器就可以通过这台NTP Server进行时间同步了

# Hosts on local network are less restricted.
#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

# 3. 上层主机的设定
# 要设定上层主机主要以 server 这个参数来设定,语法为:
# server [IP|HOST Name] [prefer]
# Server 后面接的就是我们上层 Time Server 啰!
# prefer 参数:用于标记首选服务器的选项
# iburst 参数:加速首次同步

# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
server ntp.aliyun.com  iburst

#broadcast 192.168.1.255 autokey    # broadcast server
#broadcastclient            # broadcast client
#broadcast 224.0.1.1 autokey        # multicast server
#multicastclient 224.0.1.1        # multicast client
#manycastserver 239.255.254.254        # manycast server
#manycastclient 239.255.254.254 autokey # manycast client

# Enable public key cryptography.
#crypto

includefile /etc/ntp/crypto/pw

# Key file containing the keys and key identifiers used when operating
# with symmetric key cryptography. 
keys /etc/ntp/keys

# Specify the key identifiers which are trusted.
#trustedkey 4 8 42

# Specify the key identifier to use with the ntpdc utility.
#requestkey 8

# Specify the key identifier to use with the ntpq utility.
#controlkey 8

# Enable writing of statistics records.
#statistics clockstats cryptostats loopstats peerstats

# Disable the monitoring facility to prevent amplification attacks using ntpdc
# monlist command when default restrict does not include the noquery flag. See
# CVE-2013-5211 for more details.
# Note: Monitoring will not be disabled with the limited restriction flag.
disable monitor





其他设置值,以系统默认值即可
总结一下,restrict用来设置访问权限,server用来设置上层时间服务器,driftfile用来设置保存漂移时间的文件。

启动

在启动NTP服务前,先对提供服务的这台主机手动的校正一次时间咯。(因为启动服务器,端口会被服务端占用,就不能手动同步时间了)

ntpdate ntp.aliyun.com
systemctl start ntpd 
systemctl enable  ntpd 
netstat -lntup|grep 123

验证是否正在同步

ntpstat 
synchronised to NTP server (203.107.6.88) at stratum 3
   time correct to within 964 ms
   polling server every 64 s
#该指令可列出NTP服务器是否与上层联机。
#由上述输出结果可知,时间校正约为964ms。且每隔64秒会主动更新时间。
#常见的错误:
no server suitable for synchronization found
其实,这不是一个错误。而是由于每次重启NTP服务器之后大约要3-5分钟客户端才能与server建立正常的通讯连接。当此时用客户端连接服务端就会报这样的信息。一般等待几分钟就可以了。


ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*203.107.6.88    100.107.25.114   2 u   58   64    7   22.819   -1.249   0.311
#指令“ntpq -p”可以列出目前我们的NTP与相关的上层NTP的状态,以上的几个字段的意义如下:

remote    远程NTP服务器的IP或主机名
refid    服务器同步的上层时间源(如GPS、原子钟或其他NTP服务器)
st    Stratum(层级),表示时间源的精度等级(0-15,数值越小精度越高)
t    类型:u=单播,b=广播,l=本地,s=对称节点,A=多播,B=广播
when    上次成功同步后经过的时间(分钟)
poll    轮询间隔(秒),表示与服务器同步的频率
reach    8位八进制数,表示最近8次同步的成功/失败状态(377=全部成功)
delay    网络延迟(毫秒),从本地到远程服务器的往返时间
offset    时间偏移量(毫秒),本地时钟与远程服务器的时间差异
jitter    时间偏移的波动值(毫秒),值越小表示时间越稳定



*    当前同步的源(最优时间源)
+    候选时间源(符合条件,可作为备用同步源)
-    被排除的源(因误差过大或不可靠被拒绝)
#    备用时间源(当其他源不可用时可能被选择)
o    PPS源(通过脉冲信号同步的高精度源,如GPS)
x    虚假源(时钟差异过大,可能被攻击或配置错误)
.    未使用的源(未达到候选标准)
(空格)无效或不可达的源

配置ntp硬件时间与系统时间一起同步

ntp服务,默认只会同步系统时间。如果想要让ntp同时同步硬件时间,可以设置/etc/sysconfig/ntpd文件。

在/etc/sysconfig/ntpd文件中,添加 SYNC_HWCLOCK=yes 这样,就可以让硬件时间与系统时间一起同步。

配置内网主机的时间同步实战

服务端配置

vim /etc/ntp.conf
restrict 127.0.0.1   #不可改变回环地址
restrict ::1       #不可改变回环地址
restrict 100.100.137.88    #允许客户端100.100.137.88 向本机请求时间同步
restrict 100.100.137.0 mask 255.255.255.0 nomodify  #允许客户端100.100.137.0/24 网段的所有主机向本机请求时间同步
server ntp.aliyun.com  iburst  #设置服务端的上层时间服务器,其他的注释即可,ubuntu的是pool,centos的是server

systemctl restart ntpd
systemctl enable ntpd

客户端配置

vim /etc/ntp.conf 
server 100.100.137.89 iburst    #指定上层NTP服务器

systemctl start ntpd
systemctl enable ntpd

之后使用ntpstat和ntpq -p检查是否同步即可

chrony

配置文件

cat /etc/chrony.conf
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
# 配置NTP服务器
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

# Record the rate at which the system clock gains/losses time.
# 记录系统时钟获得/丢失时间的速率至drift文件中
driftfile /var/lib/chrony/drift

# Allow the system clock to be stepped in the first three updates
# if its offset is larger than 1 second.
# 默认情况下,chronyd通过减慢或加快时钟速度来逐渐调整时钟。如果时钟与实际时间偏差太大,则需要很长时间才能纠正错误。这种方法叫做步进时钟(时间跳变)。
# 此处表示如果调整值大于1000秒,则这将使系统时钟步进,但仅在前十个时钟更新中。
makestep 1.0 3

# Enable kernel synchronization of the real-time clock (RTC).
# 启用RTC(实时时钟)的内核同步
rtcsync

# Enable hardware timestamping on all interfaces that support it.
#hwtimestamp *

# Increase the minimum number of selectable sources required to adjust
# the system clock.
#minsources 2

# 只允许192.168.网段的客户端进行时间同步
# Allow NTP client access from local network.
#allow 192.168.0.0/16

# NTP服务器不可用时,采用本地时间作为同步标准
# Serve time even if not synchronized to a time source.
#local stratum 10


# 指定包含NTP验证密钥的文件
# Specify file containing keys for NTP authentication.
#keyfile /etc/chrony.keys

# 指定日志文件的目录
# Specify directory for log files.
logdir /var/log/chrony

# 将对系统增益或损耗率的估计值以及所做的任何转换记录的更改记录到名为的文件中tracking.log。
# Select which information is logged.
#log measurements statistics tracking





# 其他未在默认配置文件的配置项
# 在第一次时钟更新之后,chronyd将检查每次时钟更新的偏移量,它将忽略两次大于1000秒的调整,并退出另一个调整。
maxchange 1000 1 2
# 该rtcfile指令定义中的文件名chronyd可以保存跟踪系统的实时时钟(RTC)的精度相关的参数。
rtcfile /var/lib/chrony/rtc

相关操作

1.检查时间是否同步

chronyc tracking
Reference ID    : DF04F950 (223.4.249.80)   #参考ID (当前同步的 NTP 服务器 IP 地址)
Stratum         : 3   #层级 (Stratum)
Ref time (UTC)  : Fri Apr 11 02:12:21 2025  #最后一次成功同步的 UTC 时间
System time     : 0.000037391 seconds slow of NTP time。#当前系统时间比 NTP 服务器时间慢约 37.39 微秒(基本可忽略,属于正常范围)
Last offset     : -0.000058851 seconds  #最后一次时钟调整时的偏移量(负值表示本地时钟比服务器慢)。
RMS offset      : 0.000058851 seconds   #时间偏移的长期平均值(约 58.85 微秒,非常低,说明同步良好)
Frequency       : 2.398 ppm fast  #系统时钟比实际时间快 2.398 百万分之一秒/秒
Residual freq   : +105.175 ppm  #未修正的时钟频率偏差(较高,可能因硬件时钟不稳定或网络延迟导致)。
Skew            : 0.085 ppm     #频率偏差的变化率(非常低,说明时钟稳定性良好)。
Root delay      : 0.043505833 seconds #与最顶层时间源(如原子钟)的总通信延迟(约 43.5 毫秒,取决于网络质量)。
Root dispersion : 0.010787953 seconds #因网络抖动和时钟漂移累积的最大误差(约 10.79 毫秒,较低)。
Update interval : 2.1 seconds  #最后一次时钟同步后的时间间隔。
Leap status     : Normal  #当前无需闰秒调整(时间同步正常)。

2.检查时间来源

chronyc sources
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^* 223.4.249.80                  2   6   377    10   -228us[ -346us] +/-   34ms

-v,显示更多

MS:源状态标记,^*当前最优源(正在使用的服务器)。^+可用的备用源。^-被排除的源(因误差过大或不可靠)。
^?未连接的源或状态未知。x    无效源(同步失败)。~    源正在初始化或测试中。
Name/IP address    NTP: 服务器的域名或 IP 地址。
Stratum:服务器的时间层级(1=原子钟直接同步,值越小越权威)。
Poll:轮询间隔(秒),值为 2^n(如 6 表示 2^6=64 秒)。
Reach:最近 8 次轮询的成功率(八进制数,377=二进制11111111,表示全部成功)。
LastRx:最后一次收到响应的时间(单位:秒或分钟)。
Last sample:最后一次时间偏移测量值(格式:实际偏移 [滤波后偏移])。
+/- error:估计的时间误差范围(单位:毫秒或微秒)。

3.检查时间来源统计,-v可以指定 可选参数,表示冗长。在这种情况下,将显示额外的标题行,以提醒各列的含义。

chronyc sourcestats
210 Number of sources = 1
Name/IP Address            NP  NR  Span  Frequency  Freq Skew  Offset  Std Dev
==============================================================================
223.4.249.80               12   8   523     +3.189      8.294   +177us  1163us

字段                       值               说明
Name/IP Address        223.4.249.80    当前同步的 NTP 服务器地址。
NP                       12            已完成的轮询(Poll)次数。
NR                       8            有效样本数(成功用于计算的响应次数)。
Span                    523            最近一次样本的时间跨度(单位:秒)。
Frequency              +3.189 ppm      本地时钟的频率偏差(正=快,负=慢)。
Freq Skew               8.294 ppm      频率偏差的估计误差范围(反映稳定性)。
Offset                +177us          当前时间偏移量(正=本地快,负=本地慢)。
Std Dev                 1163us          偏移量的标准差(波动范围,越小越稳定)。

4.手动调整系统时钟,要立即步进系统时钟,以通过回转来绕过正在进行的任何调整,如果使用该rtcfile指令,则不应手动调整实时时钟。随机调整会干扰chrony需要测量实时时钟漂移的速率。

chronyc makestep

配置内网主机的时间同步实战

搭建服务端

vim /etc/chrony.conf
server ntp1.aliyun.com iburst
allow 100.100.137.0/24
local stratum 10

systemctl restart   chronyd
chronyc sources –v
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^* 223.4.249.80                  2   6    17     4   +141us[ +677us] +/-   33ms

配置客户端

vim /etc/chrony.conf
server 100.100.137.89 iburst

systemctl restart   chronyd
chronyc sources –v
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^* 100.100.137.89                3   6    17     1    +45us[ +325us] +/-   33ms

results matching ""

    No results matching ""