网络时间(NTP)协议
NTP(Network Time Protocol) 网络时间协议,工作在UDP的123端口上。是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,它可以提供高精准度的时间校正(局域网上与标准间差小于1毫秒,互联网上几十毫秒),且可介由加密确认的方式来防止恶毒的协议攻击。
在NTP中,时间按照服务器的等级传播,Stratum-1(我们一般称作一级服务器)为最高层,其时间源为标准UTC,该时间源可以来自外部,如北斗、GPS,也可以来自该服务器内部的原子钟。而Stratum-2(二级服务器)则从Stratum-1获取时间,Stratum-3从Stratum-2获取时间,以此类推,但Stratum层的总数最多不超过15层。为防止单点故障,每一级服务器都应该有多台,且数量一般为奇数,以便于下级服务器决策。
chronyd和chronyc
Chrony是一个开源软件,它能保持系统时钟与时钟服务器(NTP)同步,让时间保持精确。它由两个程序组成:chronyd和chronyc。
chronyd是一个后台运行的守护进程,用于调整内核中运行的系统时钟和时钟服务器同步。它确定计算机增减时间的比率,并对此进行补偿。
chronyc 提供了一个用户界面,用于监控性能并进行多样化的配置。它可以在chronyd实例控制的计算机上工作,也可以在一台不同的远程计算机上工作
配置文件 示例
客户端
[root@ecs-209716 ~]# cat /etc/chrony.conf
server ntp.myhuaweicloud.com minpoll 4 maxpoll 10 iburst
# Ignore stratum in source selection.
stratumweight 0.05
# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift
# Enable kernel RTC synchronization.
rtcsync
# In first three updates step the system clock instead of slew
# if the adjustment is larger than 10 seconds.
makestep 10 3
# Allow NTP client access from local network.
#allow 192.168/16
# Listen for commands only on localhost.
bindcmdaddress 127.0.0.1
bindcmdaddress ::1
# Serve time even if not synchronized to any NTP server.
#local stratum 10
# Disable logging of client accesses.
noclientlog
# Send a message to syslog if a clock adjustment is larger than 0.5 seconds.
logchange 0.5
logdir /var/log/chrony
#log measurements statistics tracking
查看时间源
[root@ecs-209716 ~]# chronyc sources -v
.-- Source mode '^' = server, '=' = peer, '#' = local clock.
/ .- Source state '*' = current best, '+' = combined, '-' = not combined,
| / 'x' = may be in error, '~' = too variable, '?' = unusable.
|| .- xxxx [ yyyy ] +/- zzzz
|| Reachability register (octal) -. | xxxx = adjusted offset,
|| Log2(Polling interval) --. | | yyyy = measured offset,
|| \ | | zzzz = estimated error.
|| | | \
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^* 100.125.1.251 3 10 377 33 -46us[ -56us] +/- 211ms
时间相关命令
显示 时区
[root@ecs-209716 ~]# ll /etc/localtime
lrwxrwxrwx. 1 root root 35 Feb 14 2022 /etc/localtime -> ../usr/share/zoneinfo/Asia/Shanghai
显示可以配置的时区
[root@ecs-209716 ~]# timedatectl list-timezones |more
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
...
配置时区
[root@ecs-209716 ~]# timedatectl set-timezone Asia/Shanghai
显示日历
[root@ecs-209716 ~]# cal
December 2022
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
显示时间
[root@ecs-209716 ~]# date +%F
2022-12-20
获取时间戳
[root@ecs-209716 ~]# date +%s
1671525002