Configuración del servicio chrony de sincronización horaria

1. servicio cronológico

chrony es una implementación de propósito general del Protocolo de tiempo de red (NTP). Puede sincronizar el reloj del sistema con un servidor NTP, un reloj de referencia (como un receptor GPS) y entrada manual mediante un reloj y un teclado. También puede funcionar como servidor y par NTPv4 (RFC 5905), proporcionando servicios horarios a otras computadoras en la red.

Está diseñado para funcionar bien en una amplia gama de condiciones, incluidas conexiones de red intermitentes, redes muy congestionadas, temperaturas cambiantes (los relojes normales de las computadoras son sensibles a la temperatura) y sistemas que no pueden ejecutarse de manera continua o en máquinas virtuales.

La precisión típica entre dos máquinas sincronizadas a través de Internet es de unos pocos milisegundos; en una LAN, la precisión suele ser de decenas de microsegundos. La precisión de submicrosegundos puede ser posible utilizando marcas de tiempo de hardware o relojes de referencia de hardware.

Hay dos programas incluidos en chrony, chronyd es un proceso demonio que se puede iniciar en el momento del arranque y chronyc es un programa de interfaz de línea de comandos que se puede utilizar para monitorear el rendimiento de chronyd y cambiar varios parámetros operativos mientras se está ejecutando.

centos7+ admite la configuración de sincronización de hora de chrony. NTP ya no es compatible con centos8.
En comparación con la configuración de sincronización de hora de ntp, chrony es más simple y más eficiente. Es un software de código abierto que puede mantener el sistema siempre sincronizado con la hora del servidor.

2. Introducción al entorno de prueba del sistema operativo

Lado del servidor: RedHat8.2- 172.20.10.6

Cliente: CentOS8.3-172.20.10.7

Esta prueba es una instalación mínima del sistema. Después de configurar la fuente local de yum, se instala el servicio chrony (el servicio se instala tanto en el servidor como en el cliente, de la siguiente manera)

[root@centos8-3 ~]# yum install -y chrony
Last metadata expiration check: 0:00:05 ago on Tue 15 Jun 2021 08:02:45 PM CST.
Dependencies resolved.
=================================================================================================================================================================
 Package                                Architecture                        Version                                Repository                               Size
=================================================================================================================================================================
Installing:
 chrony                                 x86_64                              3.5-1.el8                              centos8-OS                              271 k
Installing weak dependencies:
 timedatex                              x86_64                              0.5-3.el8                              centos8-OS                               32 k
 
Transaction Summary
=================================================================================================================================================================
Install  2 Packages
 
Total size: 303 k
Installed size: 731 k
Downloading Packages:
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                         1/1 
  Installing       : timedatex-0.5-3.el8.x86_64                                                                                                              1/2 
  Running scriptlet: timedatex-0.5-3.el8.x86_64                                                                                                              1/2 
  Running scriptlet: chrony-3.5-1.el8.x86_64                                                                                                                 2/2 
  Installing       : chrony-3.5-1.el8.x86_64                                                                                                                 2/2 
  Running scriptlet: chrony-3.5-1.el8.x86_64                                                                                                                 2/2 
  Verifying        : chrony-3.5-1.el8.x86_64                                                                                                                 1/2 
  Verifying        : timedatex-0.5-3.el8.x86_64                                                                                                              2/2 
 
Installed:
  chrony-3.5-1.el8.x86_64                                                       timedatex-0.5-3.el8.x86_64                                                      
 
Complete!

3. Configuración del servidor y del cliente

(1) Configuración y explicación del lado del servidor (3 modificaciones)

[root@RedHat8-2 ~]# 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).
#pool 2.rhel.pool.ntp.org iburst  --注释这行,外网时间服务器的网址
server 172.20.10.6 iburst         --添加这行,表示与本机同步时间(视情况自行更改)
 
# Record the rate at which the system clock gains/losses time.
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.
makestep 1.0 3
 
# Enable kernel synchronization of the real-time clock (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
 
# Allow NTP client access from local network.
allow 172.20.10.0/28              -->>允许哪些服务器或客户端到这台时间服务器来同步时间。必须配置
# Serve time even if not synchronized to a time source.
local stratum 10                  -->>该行注释取消掉不然NTP synchronized: 为no 取消掉后变为 NTP synchronized:yes
# Specify file containing keys for NTP authentication.
keyfile /etc/chrony.keys
 
# Get TAI-UTC offset and leap seconds from the system tz database.
leapsectz right/UTC
 
# Specify directory for log files.
logdir /var/log/chrony
 
# Select which information is logged.
#log measurements statistics tracking

Inicie el servicio chrony y verifique

启动chronyd
[root@RedHat8-2 ~]# systemctl start chronyd
加入开机自启
[root@RedHat8-2 ~]# systemctl enable chronyd
 
检查
[root@RedHat8-2 ~]# netstat -antulp|grep chronyd
udp        0      0 0.0.0.0:123             0.0.0.0:*                           7745/chronyd        
udp        0      0 127.0.0.1:323           0.0.0.0:*                           7745/chronyd        
udp6       0      0 ::1:323                 :::*                                7745/chronyd        
[root@RedHat8-2 ~]# ss -antulp|grep chronyd
udp     UNCONN   0        0                0.0.0.0:123           0.0.0.0:*       users:(("chronyd",pid=7745,fd=9))                                              
udp     UNCONN   0        0              127.0.0.1:323           0.0.0.0:*       users:(("chronyd",pid=7745,fd=7))                                              
udp     UNCONN   0        0                  [::1]:323              [::]:*       users:(("chronyd",pid=7745,fd=8))                                              

(2) Configuración del cliente

[root@centos8-3 ~]# 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).
#pool 2.centos.pool.ntp.org iburst
server 172.20.10.6 iburst   -->>添加该行,表示到这台服务器去同步时间

Inicie chronyd y agregue el inicio automático al arrancar

[root@centos8-3 ~]# systemctl start chronyd
[root@centos8-3 ~]# systemctl enable chronyd

4. Verificar estado

[root@centos8-3 ~]# timedatectl 
               Local time: Tue 2021-06-15 16:45:10 CST
           Universal time: Tue 2021-06-15 08:45:10 UTC
                 RTC time: Tue 2021-06-15 16:45:10
                Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes   --表示已同步完成
              NTP service: active
          RTC in local TZ: no

5. Ver información de fuente de tiempo

Servidor

[root@RedHat8-2 ~]# chronyc sources -v
210 Number of sources = 1
 
  .-- 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               
===============================================================================
^? RedHat8-2.localdomain         0   7   377     -     +0ns[   +0ns] +/-    0ns

cliente

[root@centos8-3 ~]# chronyc sources -v
210 Number of sources = 1
 
  .-- 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               
===============================================================================
^* 172.20.10.6                  11   6   177    50  +2087ns[  -33us] +/-  227ms

6. Prueba

Instrucciones de prueba, cambie manualmente la hora en el servidor para ver si el cliente está sincronizado

(1) Ver la hora actual en el cliente y el servidor

服务端
[root@RedHat8-2 ~]# date
Tue Jun 15 16:43:22 CST 2021
 
客户端
[root@centos8-3 ~]# date
Tue Jun 15 16:43:22 CST 2021
 

(2) Cambiar manualmente la hora del servidor

[root@RedHat8-2 ~]# date 
Tue Jun 15 17:14:03 CST 2021
[root@RedHat8-2 ~]# date -s "2021-6-15 18:00:00"
Tue Jun 15 18:00:00 CST 2021

(3) Espere a que el cliente se sincronice automáticamente (el tiempo de sincronización de la prueba es relativamente lento)

[root@centos8-3 ~]# chronyc sources -v
210 Number of sources = 1
 
  .-- 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               
===============================================================================
^~ 172.20.10.6                  11   6    37    11   -2716s[ -2716s] +/-  265ms
[root@centos8-3 ~]# date
Tue Jun 15 17:16:44 CST 2021
[root@centos8-3 ~]# timedatectl 
               Local time: Tue 2021-06-15 17:16:53 CST
           Universal time: Tue 2021-06-15 09:16:53 UTC
                 RTC time: Tue 2021-06-15 09:17:19
                Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no
 
[root@centos8-3 ~]# date
Tue Jun 15 18:06:49 CST 2021

Durante la prueba, se descubrió un problema: el tiempo de sincronización fue relativamente lento, pero la sincronización se realizó con éxito.

Configurar el inicio y reiniciar el servicio

systemctl enable chronyd
systemctl restart chronyd

Utilice fuentes crónicas para ver el estado de sincronización horaria

[root@jingcheng ~]# chronyc sources
  • *Indica la fuente de reloj con la que chronyd está actualmente sincronizado

imagen

  • ? Indica una fuente que ha perdido conectividad o cuyos paquetes no pasaron todas las pruebas. También se muestra al inicio hasta que se hayan recolectado al menos 3 muestras.

imagen

  • + indica que las fuentes aceptables están agrupadas con la fuente seleccionada
  • - Indica fuentes aceptables excluidas por el algoritmo de fusión
  • x representa un reloj que chronyd considera un ticker falso (es decir, su hora es inconsistente con la mayoría de las otras fuentes).
  • ~ indica una fuente donde el tiempo parece tener demasiada variabilidad.

Ver fuentes ntp_servers:chronyc

Ver el estado de ntp_servers: chronyc sourcestats

Compruebe si ntp_servers está en línea: actividad crónica

Ver detalles de ntp: seguimiento crónico

Comandos relacionados con la hora: timedatectl
Ver fecha, hora, zona horaria y estado NTP: timedatectl
Ver lista de zonas horarias: timedatectl list-timezones
Modificar zona horaria: timedatectl set-timezone + zona horaria a modificar
Modificar fecha y hora: timedatectl set-time "Fecha a modificar"

7. Descubrimiento y resolución de problemas en la configuración de chrony.

1. ¿Aparecerá al agregar una fuente de reloj del cliente? (una fuente que ha perdido conectividad o cuyos paquetes no pasaron todas las pruebas), lo que resulta en una incapacidad para sincronizar la fuente del reloj

Solución: ① Verifique si el firewall está apagado ② Verifique si selinux está en estado permisivo o deshabilitado ③ Haga ping para ver si el enlace está abierto ④ Verifique la configuración de red ⑤ El comando permitir en la configuración de chrony no permite el acceso del cliente NTP de forma predeterminada

Supongo que te gusta

Origin blog.csdn.net/qq_36306519/article/details/130756674
Recomendado
Clasificación