目录
基础认识
常用命令
查看和修改Linux的时区
常见时区
timedatectl
时钟同步
用硬件时钟同步系统时钟:
用系统时钟同步硬件时钟:
同步网络时间
hwclock命令
语法
查看和修改Linux的时间
时钟--详解
硬件时钟
系统时钟
时间同步
时间标准
网络时间
ntp时钟同步服务
chrony时钟同步服务
chrony 命令小册子
chronyc sources 输出结果解析
备注
ntp常用服务器
基础认识
操作系统的时间(时钟)由以下4个部分决定:
时间数值时间标准(本地时间/UTC/其他)时区夏令时(DST,Daylight Saving Time,部分适用,中国已经废止)
操作系统有两个时钟,分别是硬件时钟和系统时钟,大多数操作系统的时钟管理方式如下:
启动时根据硬件时钟设置系统时钟维护准确的系统时钟关机时根据系统时钟设置硬件时钟硬件时钟是指主机板上的时钟设备,也就是通常可在BIOS画面设定的时钟。
系统时钟则是指kernel中的时钟。
常用命令
查看和修改Linux的时区
常见时区
(1)UTC整个地球分为二十四时区,每个时区都有自己的本地时间。在国际无线电通信场合,为了统一起见,使用一个统一的时间,称为通用协调时(UTC, Universal Time Coordinated)。
(2)GMT格林威治标准时间(Greenwich Mean Time)指位于英国伦敦郊区的×××格林尼治天文台的标准时间,因为本初子午线被定义在通过那里的经线。(UTC与GMT时间基本相同,本文中不做区分)
(3)CST中国标准时间(China Standard Time)
GMT + 8 = UTC + 8 = CST
(4)DST夏令时(Daylight Saving Time)指在夏天太阳升起的比较早时,将时间拨快一小时,以提早日光的使用。(中国不使用)
(1)UTC整个地球分为二十四时区,每个时区都有自己的本地时间。在国际无线电通信场合,为了统一起见,使用一个统一的时间,称为通用协调时(UTC, Universal Time Coordinated)。
(2)GMT格林威治标准时间(Greenwich Mean Time)指位于英国伦敦郊区的×××格林尼治天文台的标准时间,因为本初子午线被定义在通过那里的经线。(UTC与GMT时间基本相同,本文中不做区分)
(3)CST中国标准时间(China Standard Time)
GMT + 8 = UTC + 8 = CST
(4)DST夏令时(Daylight Saving Time)指在夏天太阳升起的比较早时,将时间拨快一小时,以提早日光的使用。(中国不使用)
1.查看当前时区
命令 : timedatectl
2.修改设置Linux服务器时区
timedatectl set-timezone Asia/Shanghai
[root@localhost etc]# timedatectlLocal time: 三 -09-15 10:04:05 CSTUniversal time: 三 -09-15 02:04:05 UTCRTC time: 三 -09-15 02:04:05Time zone: Asia/Shanghai (CST, +0800)System clock synchronized: yesNTP service: activeRTC in local TZ: no
timedatectl
[root@localhost ~]# timedatectl --helptimedatectl [OPTIONS...] COMMAND ...Query or change system time and date settings.-h --helpShow this help message--version Show package version--no-pager Do not pipe output into a pager--no-ask-passwordDo not prompt for password-H --host=[USER@]HOST Operate on remote host-M --machine=CONTAINER Operate on local container--adjust-system-clock Adjust system clock when changing local RTC mode--monitor Monitor status of systemd-timesyncd-p --property=NAME Show only properties by this name-a --all Show all properties, including empty ones--valueWhen showing properties, only print the valueCommands:status Show current time settingsshow Show properties of systemd-timedatedset-time TIME Set system timeset-timezone ZONE Set system time zonelist-timezones Show known time zonesset-local-rtc BOOL Control whether RTC is in local timeset-ntp BOOL Enable or disable network time synchronizationsystemd-timesyncd Commands:timesync-statusShow status of systemd-timesyncdshow-timesync Show properties of systemd-timesyncd
list-timezones 列出系统上支持的时区
set-timezone 设定时区
set-time 设置时间
set-btp 设置同步ntp
时钟同步
用硬件时钟同步系统时钟:
hwclock --hctosys 或者 clock --hctosys
hc代表硬件时间,sys代表系统时间,即用硬件时钟同步系统时钟
用系统时钟同步硬件时钟:
hwclock --systohc或者clock --systohc
即用系统时钟同步硬件时钟
同步网络时间
同步互联网时间
ntpdate -u cn.
hwclock命令
Linux hwclock命令用于显示与设定硬件时钟。
在Linux中有硬件时钟与系统时钟等两种时钟。
硬件时钟是指主机板上的时钟设备,也就是通常可在BIOS画面设定的时钟。
系统时钟则是指kernel中的时钟。
当Linux启动时,系统时钟会去读取硬件时钟的设定,之后系统时钟即独立运作。所有Linux相关指令与函数都是读取系统时钟的设定。
语法
hwclock [--adjust][--debug][--directisa][--hctosys][--show][--systohc][--test][--utc][--version][--set --date=<日期与时间>]
参数:
--adjust hwclock每次更改硬件时钟时,都会记录在/etc/adjtime文件中。使用--adjust参数,可使hwclock根据先前的记录来估算硬件时钟的偏差,并用来校正目前的硬件时钟。--debug 显示hwclock执行时详细的信息。--directisa hwclock预设从/dev/rtc设备来存取硬件时钟。若无法存取时,可用此参数直接以I/O指令来存取硬件时钟。--hctosys 将系统时钟调整为与目前的硬件时钟一致。--set --date=<日期与时间> 设定硬件时钟。--show 显示硬件时钟的时间与日期。--systohc 将硬件时钟调整为与目前的系统时钟一致。--test 仅测试程序,而不会实际更改硬件时钟。--utc 若要使用格林威治时间,请加入此参数,hwclock会执行转换的工作。--version 显示版本信息。
查看和修改Linux的时间
1. 查看时间和日期
命令 : "date"
2.设置时间和日期
例如:将系统日期设定成11月3日的命令
命令 : "date -s 11/03/"
将系统时间设定成下午5点55分55秒的命令
命令 : "date -s 17:55:55"
3. 将当前时间和日期写入BIOS,避免重启后失效
命令 : "hwclock -w"
时钟--详解
硬件时钟
硬件时钟,又称实时时钟(Real Time Clock,RTC)或CMOS时钟,是独立的硬件设备(电池、电容元件等),保存的时间包括年、月、日、时、分、秒。之后的UEFI固件还能保存时区和是否使用夏令时。
操作硬件时钟的工具是hwclock
,用于查询、设置硬件时钟等。
读取硬件时钟:
hwclock --show
使用系统时钟设置硬件时钟:
hwclock --systohc
更新硬件时钟后,/etc/adjtime
随之更新。
系统时钟
系统时钟,又称软件时钟,是Linux内核的一部分,包括时间、时区、夏令时(如果适用)。
系统启动时,系统时钟的初始值根据硬件时钟设定(依赖于/etc/adjtime
);
系统启动后,Linux内核利用定时器中断维护系统时钟 ,与硬件时钟无关。
操作系统时钟的工具是timedatectl
,用于查询/设置时间、设置时区、设置时间同步等。
查询时钟,其中包括本地时间、UTC时间、RTC时间、时区、系统时钟同步状态、NTP服务状态、RTC是否使用本地时间:
# timedatectlLocal time: Tue -06-02 18:08:06 CSTUniversal time: Tue -06-02 10:08:06 UTCRTC time: Tue -06-02 10:08:06 Time zone: Asia/Shanghai (CST, +0800) System clock synchronized: yes NTP service: active RTC in local TZ: no
设置时钟,时间格式是yyyy-MM-dd hh:mm:ss
:
# timedatectl set-time "-06-02 17:30:00"# timedatectlLocal time: Tue -06-02 17:30:05 CSTUniversal time: Tue -06-02 09:30:05 UTCRTC time: Tue -06-02 09:30:05 Time zone: Asia/Shanghai (CST, +0800) System clock synchronized: noNTP service: inactive RTC in local TZ: no
时间字符串为本地时间,执行命令后,本地时间、UTC时间、RTC时间会同时更新。
开启时间同步:
timedatectl set-ntp 1
时间同步
可以使用ntpd -qg
命令同步时间。
另外,Linux系统自带ntpd.service,可以使用systemctl start ntpd
命令启动NTP服务。
需要注意的是,ntpd
命令或服务仅更新本地时间和UTC时间,不更新RTC时间。 可以设置一个过去的时间,然后执行ntpd
命令校准时间,再执行timedatectl
命令查询验证。
不过这并不是什么大问题,因为关机时操作系统会根据系统时钟重设硬件时钟,下次启动时,二者恢复一致。
时间标准
两种时间标准:
本地时间(时区相关)UTC时间(时区无关)
硬件时钟所采用的时间标准是由操作系统决定的,默认情况下,Windows使用本地时间,macOS使用UTC时间,类Unix系统则各有不同。
使用UTC时间标准的操作系统通常把硬件时钟视为UTC,然后在启动时根据时区进行调整设置系统时间。
如果一台机器上安装了多个操作系统,它们都使用硬件时钟设置系统时间,建议采用统一的UTC时间标准,避免切换系统时发生时间错乱。
网络时间
ntpdate命令用于同步更新互联网时间,或者NTP服务器时间
NTP服务器【Network Time Protocol(NTP)】是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,它可以提供高精准度的时间..
ntp时钟同步服务
centos7以上版本对如下命令已经不能用:
yum install ntp# 报如下错,Error: Unable to find a match# 使用如下方法 安装ntp服务# 添加源rpm -ivh /centos/wlnmp-release-centos.noarch.rpm# 安装ntp服务dnf install wntp# 时间同步ntpdate
chrony时钟同步服务
适用于centos7以上版本
chrony是网络时间协议(NTP)的通用实现。它可以将系统时钟与NTP服务器,参考时钟(例如GPS接收器)以及使用手表和键盘进行的手动输入进行同步。它还可以充当NTPv4(RFC 5905)服务器并与之同行,以向网络中的其他计算机提供时间服务。
它被设计为在各种条件下均能良好运行,包括间歇性网络连接,网络严重拥塞,温度变化(普通计算机时钟对温度敏感)以及无法连续运行或在虚拟机上运行的系统。
通过Internet同步的两台计算机之间的典型精度在几毫秒内;在LAN上,精度通常为数十微秒。使用硬件时间戳记或硬件参考时钟,亚微秒精度是可能的。
chrony包括两个程序,
chronyd一个是守护程序,可以在引导时启动,chronyc另一个是命令行界面程序,可以用来监视其chronyd性能并在运行时更改各种操作参数。
目前centos7已经默认安装chrony3.2作为时钟服务。
安装chronyd服务
# 操作主机:所有主机yum -y install chrony# 备份旧配置文件cp /etc/chrony.conf /etc/chrony.$(date +'%s')
配置chronyd服务器
# 操作主机:chronyd服务器 # 修改服务器配置⽂件,以阿⾥云时间服务器为上游服务器cat > /etc/chrony.conf <<_EOFserver iburstserver iburstdriftfile /var/lib/chrony/driftmakestep 1.0 3rtcsynclocal stratum 10logdir /var/log/chrony_EOF
启动chrony服务
# 3. 启动chronydsystemctl start chronydsystemctl enable chronyd# 查看时间同步状态timedatectl status# 开启网络时间同步timedatectl set-ntp true
检查阿里云时钟服务状态
[root@localhost bigunion]# chronyc sources210 Number of sources = 2MS Name/IP address Stratum Poll Reach LastRx Last sample===============================================================================^* 120.25.115.20 2 10 367 410 +2787us[+3511us] +/- 18ms^+ 203.107.6.88 2 10 377 438 -547us[ +176us] +/- 23ms
查看123和323端口是否监听
chrony配置参数说明
服务unit文件: /usr/lib/systemd/system/chronyd.service
监听端口: 323/udp,123/udp
配置文件: /etc/chrony.conf
server: 该参数可以多次用于添加时钟服务器,必须以"server "格式使用。可以添加任意个时间服务器。stratumweight: stratumweight指令设置当chronyd从可用源中选择同步源时,每个层应该添加多少距离到同步距离。默认情况下,CentOS中设置为0,让chronyd在选择源时忽略源的层级。driftfile: 根据实际时间计算出计算机增减时间的比率,将它记录到一个文件中是最合理的,在重启后为系统时钟作出补偿,甚至可能的话,会从时钟服务器获得较好的估值。rtcsync: rtcsync指令将启用一个内核模式,在该模式中,系统时间每11分钟会拷贝到实时时钟(RTC)。allow/deny: 这里你可以指定一台主机、子网,或者网络以允许或拒绝NTP连接到扮演时钟服务器的机器。例:allow 192.168.0.10deny 192.168.2.10cmdallow/cmddeny: 指定哪个IP地址或哪台主机可以通过chronyd使用控制命令。bindcmdaddress : 该指令允许你限制chronyd监听哪个网络接口的命令包(由chronyc执行)。该指令通过cmddeny机制提供了一个除上述限制以外可用的额外的访问控制等级。例:bindcmdaddress 127.0.0.1bindcmdaddress ::1makestep: chronyd将根据需求通过减慢或加速时钟,使得系统逐步纠正所有时间偏差。在某些特定情况下,系统时钟可能会漂移过快,导致该调整过程消耗很长的时间来纠正系统时钟。该指令强制chronyd在调整期大于某个阀值时步进调整系统时钟,但只有在因为chronyd启动时间超过指定限制(可使用负值来禁用限制),没有更多时钟更新时才生效。makestep 1.0 3 如果系统时钟的偏移量大于1秒,则允许系统时钟在前三次更新中步进。
常见参数如上,实际参数还有很多,可以在官网查看。
/documentation.html
chrony 命令小册子
查看 ntp_servers
chronyc sources -v
查看 ntp_servers 状态
chronyc sourcestats -v
查看 ntp_servers 是否在线
chronyc activity -v
查看 ntp 详细信息
chronyc tracking -v
强制同步下系统时钟
chronyc -a makestep
[root@localhost etc]# chronyc --helpUsage: chronyc [-h HOST] [-p PORT] [-n] [-c] [-d] [-4|-6] [-m] [COMMAND][root@localhost etc]# chronyc helpSystem clock:trackingDisplay system time informationmakestepCorrect clock by stepping immediatelymakestep <threshold> <updates>Configure automatic clock steppingmaxupdateskew <skew> Modify maximum valid skew to update frequencywaitsync [<max-tries> [<max-correction> [<max-skew> [<interval>]]]]Wait until synchronised in specified limitsTime sources:sources [-v]Display information about current sourcessourcestats [-v] Display statistics about collected measurementsreselectForce reselecting synchronisation sourcereselectdist <dist> Modify reselection distanceNTP sources:activityCheck how many NTP sources are online/offlinentpdata [<address>] Display information about last valid measurementadd server <address> [options]Add new NTP serveradd peer <address> [options]Add new NTP peerdelete <address> Remove server or peerburst <n-good>/<n-max> [<mask>/<address>]Start rapid set of measurementsmaxdelay <address> <delay> Modify maximum valid sample delaymaxdelayratio <address> <ratio>Modify maximum valid delay/minimum ratiomaxdelaydevratio <address> <ratio>Modify maximum valid delay/deviation ratiominpoll <address> <poll> Modify minimum polling intervalmaxpoll <address> <poll> Modify maximum polling intervalminstratum <address> <stratum>Modify minimum stratumoffline [<mask>/<address>] Set sources in subnet to offline statusonline [<mask>/<address>] Set sources in subnet to online statusonoffline Set all sources to online or offline statusaccording to network configurationpolltarget <address> <target>Modify poll targetrefresh Refresh IP addressesManual time input:manual off|on|reset Disable/enable/reset settime commandmanual list Show previous settime entriesmanual delete <index> Delete previous settime entrysettime <time> Set daemon time(e.g. Sep 25, 16:30:05 or 16:30:05)NTP access: accheck <address> Check whether address is allowedclients Report on clients that have accessed the serverserverstats Display statistics of the serverallow [<subnet>] Allow access to subnet as a defaultallow all [<subnet>] Allow access to subnet and all childrendeny [<subnet>] Deny access to subnet as a defaultdeny all [<subnet>] Deny access to subnet and all childrenlocal [options] Serve time even when not synchronisedlocal off Don't serve time when not synchronisedsmoothtime reset|activate Reset/activate time smoothingsmoothing Display current time smoothing stateMonitoring access:cmdaccheck <address> Check whether address is allowedcmdallow [<subnet>] Allow access to subnet as a defaultcmdallow all [<subnet>]Allow access to subnet and all childrencmddeny [<subnet>]Deny access to subnet as a defaultcmddeny all [<subnet>]Deny access to subnet and all childrenReal-time clock: rtcdata Print current RTC performance parameterstrimrtc Correct RTC relative to system clockwritertcSave RTC performance parameters to fileOther daemon commands:cyclelogs Close and re-open log filesdump Dump all measurements to save filesrekey Re-read keys from key fileshutdownStop daemonClient commands: dns -n|+n Disable/enable resolving IP addresses to hostnamesdns -4|-6|-46Resolve hostnames only to IPv4/IPv6/both addressestimeout <milliseconds>Set initial response timeoutretries <retries> Set maximum number of retrieskeygen [<id> [<type> [<bits>]]]Generate key for key fileexit|quit Leave the programhelp Generate this help
chronyc sources 输出结果解析
[root@localhost etc]# chronyc chrony version 3.5Copyright (C) 1997-, , - Richard P. Curnow and otherschrony comes with ABSOLUTELY NO WARRANTY. This is free software, andyou are welcome to redistribute it under certain conditions. See theGNU General Public License version 2 for details.chronyc> sources -v210 Number of sources = 2.-- Source mode '^' = server, '=' = peer, '#' = local clock./ .- Source state '*' = current synced, '+' = combined , '-' = not combined,| / '?' = unreachable, 'x' = time may be in error, '~' = time too variable.|| .- 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===============================================================================^* 120.25.115.20 2 6 377 25 -1078us[-1292us] +/- 19ms^- 203.107.6.88 2 6 377 25 -5231us[-5445us] +/- 23mschronyc> exitexit
M
这表示信号源的模式。^表示服务器,=表示对等方,#表示本地连接的参考时钟。
S
此列指示源的状态。
* 表示chronyd当前同步到的源。+ 表示可接受的信号源,与选定的信号源组合在一起。- 表示被合并算法排除的可接受源。? 指示已失去连接性或其数据包未通过所有测试的源。它也显示在启动时,直到从中至少收集了3个样本为止。x 表示chronyd认为是虚假行情的时钟(即,其时间与大多数其他来源不一致)。〜 表示时间似乎具有太多可变性的来源。
Name/IP address
这显示了源的名称或IP地址,或参考时钟的参考ID。
Stratum
这显示了来源的层,如其最近收到的样本中所报告的那样。层1表示一台具有本地连接的参考时钟的计算机。与第1层计算机同步的计算机位于第2层。与第2层计算机同步的计算机位于第3层,依此类推。
Poll
这显示轮询源的速率,以秒为单位的时间间隔的以2为底的对数。因此,值为6表示每64秒进行一次测量。chronyd会根据当前情况自动更改轮询速率。
Reach
这显示了源的可达性寄存器以八进制数字打印。寄存器有8位,并在每个从源接收或丢失的数据包上更新。值377表示从最后八次传输中收到了对所有用户的有效答复。
LastRx
此列显示多长时间前从来源接收到了最后一个好的样本(在下一列中显示)。未通过某些测试的测量将被忽略。通常以秒为单位。字母m,h,d或y表示分钟,小时,天或年。
Last sample
此列显示上次测量时本地时钟与源之间的偏移。方括号中的数字表示实际测得的偏移量。可以用ns(表示纳秒),us(表示微秒),ms(表示毫秒)或s(表示秒)作为后缀。方括号左侧的数字表示原始测量值,已调整为允许此后施加于本地时钟的任何摆度。
+/-指示器后面的数字表示测量中的误差范围。正偏移表示本地时钟位于源时钟之前。
备注
ntp常用服务器
国内:
cn. 中国开源免费NTP服务器 阿里云 阿里云NTP服务器 阿里云NTP服务器 阿里云NTP服务器 阿里云NTP服务器210.72.145.44 国家授时中心s1a. 北京邮电大学s1b. 清华大学s1c. 北京大学s1d. 东南大学s1e. 清华大学s2a. 清华大学s2b. 清华大学s2c. 北京邮电大学s2d. 西南地区网络中心s2e. 西北地区网络中心s2f. 东北地区网络中心s2g. 华东南地区网络中心s2h. 四川大学网络管理中心s2j. 大连理工大学网络中心s2k. CERNET桂林主节点s2m. 北京大学ntp. 202.120.2.101 上海交通大学
国外:
苹果NTP服务器 苹果NTP服务器 苹果NTP服务器 苹果NTP服务器 苹果NTP服务器 谷歌NTP服务器 谷歌NTP服务器 谷歌NTP服务器 谷歌NTP服务器 开源免费NTP服务器
参考文档
System time - ArchWiki/documentation.html