DATAENGINER

DATAENGINER Хостинг

The
Network Time Protocol (NTP) is a networking protocol for system clock synchronization with remote internet time servers or other sources such as GPS or radio clocks. Accurate timekeeping is crucial in servers for application to work correctly or troubleshooting issues with the help of logs time stamp.

Chrony is an implementation of NTP, and it is a replacement for the old
Ntpd used in previous versions of enterprise Linux operating systems.

Here, we will see how to install
NTP (Chrony) On
CentOS 8 /
CentOS 7 &
RHEL 8 /
RHEL 7.

Chrony works as the default NTP server and client on CentOS 8 / RHEL 8. In CentOS 7/ RHEL 7, you have an option to choose either NTP or Chrony as an NTP daemon.

NTP(Network Transfer Protocol) is a protocol that is used for the synchronization of time over a network. It provides the service of setting the current time on the client’s request so that the client can set his clock on his system. There are three tiers of NTP servers:

  • Tier 1: Connected to atomic clocks.
  • Tier 2 and Tier 3: Carry the load of handling the requests all over the Internet.
  • На главную
  • Категории
  • Операционные системы

DATAENGINER

Для чего это делать? Это делается для того, чтобы на вашем сервере было точное время. А если у вас в сети есть несколько серверов — то это просто необходимая вещь. У меня, к примеру, есть несколько zabbix proxy и 1 zabbix server и чтобы данные не разнились, то необходимо, чтобы на все этих серверах было одинаковое время. Время можно синхронизировать в интернете или со своим сервером времени (как это сделано у меня). Про настройку своего сервера времени мы поговорим отдельно. Сейчас разберемся, как настроить свои сервера на синхронизацию времени.

Так же вы можете почитать про установку CentOS 7, настройку сети в CentOS 7 и как добавлять пользователей в CentOS 7.

  • SYNOPSIS
  • ntpdate command examples in Linux(RHEL/CentOS 7/8)

There are other ntp utilities like ntpq, ntpstat which are used along with ntpdate to check and synchronizes the local server time with the NTP Server. Here we will keep our focus on ntpdate command and will see the usage of this command with examples.

The example discussed below is for a basic NTP server and client. NTP stands for Network Transport Protocol and it is used to keep the time on the servers synced with each other using a common reliable source to get the time.

Содержание
  1. NTP Server Configuration
  2. NTP Client Configuration
  3. Change the current date and time
  4. Change Time Zone
  5. Configuring NTP
  6. NTP vs Chrony
  7. Migrating from NTP to chrony
  8. Установка Chrony на RHEL 8/CentOS 8
  9. Настройка Chrony на RHEL 8/CentOS 8
  10. Настройка NTP-клиент на CentOS 8/RHEL 8
  11. Синхронизация времени через chroony
  12. Installing Chrony
  13. Starting chrony
  14. Verify
  15. Stop chrony
  16. Prerequisites
  17. Update Your Server
  18. Install NTP Packages
  19. Configure NTP Servers
  20. Check NTP Synchronization Status
  21. Verify date and time
  22. Remove NTP Package
  23. What is NTP?
  24. NTP service installation and configuration
  25. We can select NTP Pool Server list from pool ntp site
  26. Now we need to add our network which we want to allow
  27. NTP service Logs enable
  28. NTP Server Configuration has been completed
  29. We need to add Firewall Rules for NTP service
  30. Now we need to enable and start our NTP server.
  31. Now we can Verify NTP Server Time Sync
  32. Check with timedatectl command
  33. Now our NTP server has been successfully installed and configured.
  34. Configure NTP Client on Linux server
  35. After package installation we need to add NTP server IP in /etc/ntp. conf file like this
  36. After that we need to enable and start our ntp service on NTP client. Like this
  37. That’s all we have completed NTP server and NTP Client installation and Configuration.
  38. Steps for NTP configuration in CentOS
  39. Install the NTP package
  40. Configuring the NTP server
  41. Restarting the ntpd service
  42. Check the Sync status of NTP
  43. Final verification of time and date
  44. Querying about the delay and offset
  45. Install Chrony On CentOS 8 / CentOS 7 & RHEL 8 / RHEL 7
  46. Configure NTP Server Using Chrony
  47. Configure NTP Client Using Chrony
  48. SYNOPSIS
  49. How to Check If Client machine is sync with NTP Server
  50. How to Test Connection to a NTP Server
  51. How to divert Connection output to the System Logs
  52. How to Synchronize Connection to a NTP Server
  53. How to Enable Debugging Mode
  54. How to Use Verbose Mode with ntpdate command in Linux
  55. How to Force Step up the time rather than adjust Using ntpdate command
  56. How to Force the Time Sync to always be slewed
  57. How to Check Man Page of ntpdate command in Linux
  58. Настройка NTP на CentOS 7

NTP Server Configuration

1. Install the required ntp package on the server.

# cat /etc/ntp.conf
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict -6 ::1
server 0.pool.ntp.org
server 1.pool.ntp.org
server 2.pool.ntp.org
server 3.pool.ntp.org
restrict 10.10.10.0 mask 255.255.255.0 nomodify notrap
driftfile /var/lib/ntp/drift
keys /etc/ntp/keys

As per the configuration file the NTP servers servers only to the NTP clients in the subnet 10.10.10.0/24. You can get the public NTP servers specific to your region from pool.ntp.org.

In the /etc/ntp.conf file you will have to mention the NTP server(s) in your environment.

3. Now you can start the ntpd service.
For RHEL 5,6:

For RHEL 7:

# systemctl start ntpd.service

NTP Client Configuration

1. For client NTP configuration, add the below configuration in the /etc/ntp.conf file.

# cat /etc/ntp.conf
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict -6 ::1
server ntp.server.com
driftfile /var/lib/ntp/drift
keys /etc/ntp/keys

Here, ntp.server.com is the server you configured as NTP server in the example shown at the start of the post. There can be multiple NTP servers for redundancy purpose. Add a new line for each of the NTP servers in the /etc/ntp.conf file.

2. Start the ntpd service on the ntp client server.
For RHEL 5,6:

RHEL 7 offers another utility to configure and display date and time information, timedatectl. This utility is part of the systemd system and service manager. With the timedatectl command you can :

  • Change the current date and time
  • Set the time zone
  • Configure NTP

If you run timedatectl without any options, you would get an output similar to below :

# timedatectl
Local time: Sun 2017-09-24 13:16:39 IST
Universal time: Sun 2017-09-24 07:46:39 UTC
RTC time: Sun 2017-09-24 07:46:39
Time zone: Asia/Kolkata (IST, +0530)
NTP enabled: no
NTP synchronized: yes
RTC in local TZ: no
DST active: n/a

The above output shows – local time, universal time, RTC time, time zone, NTP configuration and Daylight Savings Time (DST)

Change the current date and time

Use the set-time argument to change the current date and the current time.

# timedatectl set-local-rtc yes

# timedatectl set-local-rtc no

Change Time Zone

# timedatectl set-timezone Asia/Kolkata

Configuring NTP

# timedatectl set-ntp yes

In CentOS/RHEL 8, ntp is no longer supported. chrony is enabled by default. For this reason, you might need to migrate from ntp to chrony.

In standard CentOS/RHEL 8 servers, chrony should be installed and active already. It can be verified by executing:

# systemctl status chronyd

● chronyd.service — NTP client/server
Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2021-01-25 16:31:25 GMT; 2 days ago
Docs: man:chronyd(8)
man:chrony.conf(5)
Process: 1401 ExecStartPost=/usr/libexec/chrony-helper update-daemon (code=exited, status=0/SUCCESS)
Process: 1388 ExecStart=/usr/sbin/chronyd $OPTIONS (code=exited, status=0/SUCCESS)
Main PID: 1397 (chronyd)
Tasks: 1 (limit: 100197)
Memory: 2.0M
CGroup: /system.slice/chronyd.service
└─1397 /usr/sbin/chronyd

The chronyc command can be used as the client, for example to check for the existing sources with:

And in the unlikely event that chrony is not installed, the package can be installed via yum, by installing chrony:

NTP vs Chrony

Below is an summary of comparison between NTP and chrony:

Migrating from NTP to chrony

Below is an example of converting your NTP configuration to chrony using the script:

Читайте также:  Как перенести сайт на хостинг

Here,
-b – backups original /etc/chrony.conf or /etc/chrony.keys before making any changes.
-v – versbose printing.

Any unsupported directives from ntp.conf are included in the chrony.conf as comments.

DATAENGINER

Это руководство поможет вам установить и настроить NTP-сервер с помощью Chrony на RHEL 8/CentOS 8.  NTP (сетевой протокол времени) — это сетевой протокол, который позволяет синхронизировать часы между компьютерными системами.

О том, как установить prometheus, вы можете прочитать здесь.

Chrony — это универсальная реализация протокола сетевого времени. У него есть две программы  chronyи  chronyd.

  • chronyd  — это демон, который может быть запущен во время загрузки
  • chronyc это программа интерфейса командной строки, которая может использоваться для мониторинга  chronydпроизводительности и изменения различных рабочих параметров во время работы.

Установка Chrony на RHEL 8/CentOS 8

Подключимся по ssh, к нашей виртуальной машине.

Установим часовой пояс. В моей случае я установлю часовой пояс Europe/Moscow, затем проверим временную зону:

DATAENGINER

Chrony содержит в репозиториях CentOS, поэтому выполним его установку используя пакетный менеджер DNF:

dnf install chrony -y

DATAENGINER

После установки запустим и включим службу chronyd.

systemctl enable —now chronyd

Статус сервиса должен отображаться running

DATAENGINER

Настройка Chrony на RHEL 8/CentOS 8

После установки вы можете внести изменения в основной файл конфигурации Chrony в файле /etc/chrony.conf

Одно из основных изменений конфигурации, которое вы можете сделать — это установить серверы времени ближе всего к вам. Поскольку я живу в России, я установлю пул серверов NTP в ВНИИФТРИ.

Для этого я отредактирую файл /etc/chrony.conf закомментирую первую строку и добавлю следующий список серверов:

Файл примет вид.

DATAENGINER

Установим синхронизацию NTP.

timedatectl set-ntp true
systemctl restart chronyd.service

Перезапустим chronydсервис после внесения изменений:

DATAENGINER

Если вы используете включенный фаерволл, то откройте порт который будет использовать chrony для работы с ntp серверами и не забудьте перезагрузить фаерволл для того, чтобы правила вступили в силу:

firewall-cmd —add-service=ntp —permanent 
firewall-cmd —reload

DATAENGINER

Проверим, работает ли NTP-сервер.

DATAENGINER

Настройка NTP-клиент на CentOS 8/RHEL 8

Теперь, когда у вас установлен и настроен NTP-сервер Chrony, вы можете настроить NTP-клиент.

Установите часовой пояс на виртуальной машине с которой необходимо синхронизировать время.

DATAENGINER

Установим Chrony и настройте его как клиента NTP.

DATAENGINER

Отредактируем файл конфигурации, чтобы настроить NTP-сервер так, чтобы он указывал на вновь настроенный NTP-сервер.

DATAENGINER

DATAENGINER

Запустим и включим сервис chrony.

DATAENGINER

Проверьте настройку с помощью следующей команды:

NTP (англ. Network Time Protocol — протокол сетевого времени) — сетевой протокол для синхронизации внутренних часов компьютера с использованием сетей с переменной латентностью. Протокол был разработан Дэвидом Л. Миллсом, профессором Делавэрского университета, в 1985 году.

Рассмотрим 2 утилиты синхронизации времени в Centos:

  • ntp / ntpdate
  • chroony

Установим софт из стандартного репозитория

Выполним синхронизацию вручную

Чтобы просто запросить сервер и не устанавливать часы выполним команду ntpdate со следующими флагами

Для установки нужных серверов синхронизации времени отредактируем файл ntp.conf, и вместо серверов по-умолчанию можно прописать нужные

Активируем NTP client и проверим статус

Для проверки системных часов надо ввести команду date

Синхронизация времени через chroony

По-умолчанию в Centos 7 minimal синхронизация времени не настроена

Для изменения серверов синхронизации времени надо отредактировать файл /etc/chrony.conf

Запускаем сервис и добавляем его в автозагрузку

Проверяем, активировалась ли синхронизация

У блога появился хостинг, его любезно предоставила компания Облакотека. Облакотека — облачные сервисы для создания и управления виртуальной ИТ-инфраструктурой.
Если вам понравился мой блог и вы хотели бы видеть на нем еще больше полезных статей, большая просьба поддержать этот ресурс.

Если вы размещаете материалы этого сайта в своем блоге, соц. сетях, и т.д., убедительная просьба публиковать обратную ссылку на оригинал

Installing Chrony

# systemctl start chronyd
# systemctl enable chronyd

A sample configuration would look like below :

Although, all these parameters are not required. For this post purpose I am using only below two lines in the configuration file.

# cat /etc/chrony.conf
server 192.0.2.1
allow 192.0.2/24

Starting chrony

Use the systemctl command to start the chrony daemon, chronyd.

Verify

# chronyc tracking
Reference ID : 192.0.2.1 (192.0.2.1)
Stratum : 12
Ref time (UTC) : Fri Aug 05 19:06:51 2016
System time : 0.000823375 seconds fast of NTP time
Last offset : 0.001989304 seconds
RMS offset : 0.060942811 seconds
Frequency : 1728.043 ppm slow
Residual freq : 1.100 ppm
Skew : 94.293 ppm
Root delay : 0.000207 seconds
Root dispersion : 0.016767 seconds
Update interval : 65.1 seconds
Leap status : Normal

Run the chronyc sources command to display information about the current time sources that chronyd is accessing.

Some of the fields are described:
M: The mode of the source. ^ means a server, = means a peer, and # indicates
a locally connected reference clock.
S: The state of the sources. “*” indicates the source to which chronyd is currently synchronized. “+” indicates acceptable sources that are combined with the selected source. “-” indicates acceptable sources that are excluded by the combining algorithm. “?” indicates sources to which connectivity has been lost or whose packets do not pass all tests. “x” indicates a clock that chronyd thinks is a false ticker, that is, its time is inconsistent with a majority of other sources. “~” indicates a source whose time appears to have too much variability. The “?” condition is also shown at start-up, until at least three samples have been gathered from it.
Name/IP address: This shows the name or the IP address of the source, or reference ID for reference clocks.

Run the chronyc sourcestats command. This command displays information about the drift rate and offset estimation
process for each of the sources currently being examined by chronyd.

# chronyc sourcestats
210 Number of sources = 1
Name/IP Address NP NR Span Frequency Freq Skew Offset Std Dev
==================================================================================
192.0.2.1 5 4 259 -747.564 1623.869 -2873us 30ms

Stop chrony

Use the systemctl command to stop the chrony daemon, chronyd.

Run the chronyc tracking command and notice chronyc cannot talk to the chronyd daemon.

# chronyc tracking
506 Cannot talk to daemon

In this article, we will look into how to configure NTP Server on RHEL/CentOS 7/8 Using 7 Easy Steps. If you are working in any of the Cluster environment then you might be aware of the importance of having clock synced between all the nodes in a Cluster. Generally, a cluster requires a setup from where all its nodes can sync its clock. Any drift in clock might push application to non working state causing huge production loss.

You can also set the clock date and time manually using date and timedatectl commands but every Server hardware has a tendency of clock drifting over a period of time. Hence setting up the date and time manually might not always be a viable solution especially in a cluster environment. Instead one can easily think to configure NTP Server from where all the nodes can synchronize its date and time without much resource utilization. I will explain more about the steps to configure NTP Server in below sections.

DATAENGINER

10 Practical and Useful ntpq Command Examples in Linux(RHEL/CentOS 7/8)

Prerequisites

a) You require a running RHEL/CentOS 7/8 Server.

b) You should have yum installed in your Server. You can check Top 22 YUM command examples in RedHat/CentOS 7 to know more about yum command.

Update Your Server

If you have not updated your Server from quite some time then it will always recommended to first update your installed packages with the latest updates before installing any new package. You can use the yum utility and run yum update -y command to download and install all the latest updates from CentOS Repo.

Install NTP Packages

In the next step you can install NTP package by using yum install ntp -y command as shown below. This will download and install ntp package along with its dependencies.

Configure NTP Servers

NTP configuration is usually found under /etc path. To add NTP Server information in /etc/ntp.conf file we need to open the file with our favorite vi editor and provide the NTP Server IP or hostname with server keyword as shown below. You can also add the Server information at the end of the file and then save and close the file by pressing Esc and then :wq!

Читайте также:  Majordomo скачать

In the steps to configure NTP Server you might also want to restrict the NTP Server access for some of the clients. This can be accomplished by using below configuration in /etc/ntp.conf file. Here you need to replace the network information with the client network and their subnet mask information. This will restrict the given Client access.

restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

Once we have the configuration file saved and if all the other entries are correct then you can go ahead and start/restart the ntpd service to updates the changes using service ntpd restart or systemctl restart ntpd command depends upon you are using SysV or SystemD.

If you want the ntpd service to survive the system restart then you need to enable the service as well by using chkconfig or systemctl command depends on SysV or SystemD you are using.

Check NTP Synchronization Status

In the next step you can wait for the Server to sync its time with NTP Server and then check the synchronization status by using ntpq -np command as shown below.

Output all host addresses in dotted-quad numeric format rather than converting to the canonical host names.

Print a list of the peers known to the server as well as a summary of their state. More on ntpq Page.

Verify date and time

If everything went well then Your date and time should synchronized from the NTP Server. You can verify your timezone, date and time by using timedatectl command as shown below. Alternatively, you can also use date command to verify date and time.

If you want to query from NTP Server and check the current offset and delay then you can do it by using ntpdate command. For example here we are querying local server clock offset and delay from CentOS NTP Server pool.ntp.org by using ntpdate -q pool.ntp.org command as shown below.

Remove NTP Package

Like installation you can also remove the NTP package easily from your Server by using yum remove ntp -y command as shown below.

In this tutorial, I am going to show you, NTP installation and configuration on CentOS 7 and RHEL 7. We will configure automatically synchronize time with the closest geographically peers available for our server location by using NTP Public Pool Time Servers list. So let’s start.

What is NTP?

NTP stand for Network Time Protocol. NTP is used for clock synchronization between computers system over networks. It’s run over port 123 UDP at Transport Layer.

NTP service installation and configuration

You can see here our NTP service has been successfully installed.

We can select NTP Pool Server list from pool ntp site

After successfully NTP service installation, We need to go to official NTP Public Pool Time Servers, choose your continent area where the server physically is located, then search for your country location after that you can see NTP servers list for selected country. Like this:-

DATAENGINER

After NTP server selection, we have to edit our NTP service configuration file. You can find NTP configuration file on this path:- /etc/ntp.conf. So let’s start NTP configuration. First of all we have to comment the default list of Public Servers from pool.ntp.org project and replace it with the list provided for your country like below configuration in bold:-

Here is our public NTP Server has been configured in ntp.conf file.

Now we need to add our network which we want to allow

The nomodify notrap statements suggest that your clients are not allowed to configure the server or be used as peers for time sync.

NTP service Logs enable

If you want to additional information for troubleshooting in case there is any issue with your NTP service then you can add a log file statement which will allow to record all NTP server logs into one dedicated log file. You can add log file /var/log/ntp.log at the end of ntp.conf file. Like this:-

NTP Server Configuration has been completed

After all above mandatory configuration changes, we can save ntp.conf file. Our final configuration should be look like this in the below screenshot. In below yellow line is our final configuration.

We need to add Firewall Rules for NTP service

NTP service uses UDP port 123 on OSI transport layer (layer 4). We can run this below commands to open 123 port on RHEL7 / CentOS 7 against Firewalld service.

Now port has been successfully open from system firewall.

Now we need to enable and start our NTP server.

After that we can start NTP server and make sure ntpd server should be enable at the server boot time. So once your server will restart, NTP server automatically start. You can use below commands to start the ntpd service and enable ntpd service at the boot time.

You can see here our NTP server has been successfully start.

Now we can Verify NTP Server Time Sync

Here you can see NTP Time Sync successfully.

Synchronize NTP Time has been done with NTP pool server.

Check with timedatectl command

You can also check with timedatectl command and your NTP enabled and NTP synchronized should be yes on your NTP server look like this:-

If your NTP synchronized is no then you have to enable with below commands. First you have stop your NTP server and then you have to try to enable NTP synchronized once this enabled you have to start NTP service. Like this:-

Now our NTP server has been successfully installed and configured.

After that our windows will be sync with our NTP server.

Configure NTP Client on Linux server

Now I am going to show you how to configure NTP client on Linux7 and CentOS7. We need to install ntp package on client as like NTP server.

After package installation we need to add NTP server IP in /etc/ntp. conf file like this

DATAENGINER

After that we need to enable and start our ntp service on NTP client. Like this

Now you have to check with timedatectl command and your  output will be look like below. If there is any different you can perform above NTP server timedateclt steps to correct it.

After that you can see you client date automatically sync with your NTP server.

That’s all we have completed NTP server and NTP Client installation and Configuration.

You can also check with below link how to configure DNS on CentOS 7 and RHEL 7

Steps for NTP configuration in CentOS

Updating the system and having the latest version of all the packages is an important part as we might get stuck in the later part of the installation. Use the yum package manager to update the system.

DATAENGINER

Install the NTP package

After updating the system, install the NTP package by using the below command:

DATAENGINER

Configuring the NTP server

The information about the NTP configuration file resides in the /etc PATH. To add this information to the ntp.conf file we have to edit this file in the editor. We have to add the NTP server name and the IP address. Open the file using the below command. To get the servers of our region and timezone visit this site: https://www.pool.ntp.org/en/

Select your region and comment down the servers that are already in the file, and add down your servers.

vi /etc/ntp.conf

DATAENGINER

This is how the .conf file looks.

DATAENGINER

DATAENGINER

The highlighted portion in red signifies the available servers that will be used for syncing purposes. Save the file with :wq, and exit.

Restarting the ntpd service

Now that we have made the relevant changes we have to restart the ntpd service to make these changes effective. Use the below command:

Читайте также:  Будьте защищены: обновите Windows 7 RDP с помощью этого патча

DATAENGINER

Check the Sync status of NTP

In this step we will check the status of synchronization of the NTP server, by using the below command:

DATAENGINER

Meaning of the -n and -p flags:

  • -n: This is used for displaying the output of all the host addresses in a dotted-quad format.
  • -p: This is used to display the peers which are identified by the server.

Final verification of time and date

After completing all the above steps, we should get the correct date and time according to our zone. We can confirm that by using the below command:

DATAENGINER

The date command can also be used to verify the date and time.

DATAENGINER

Querying about the delay and offset

If we want to get info about offsets, and delays from the NTP server then we can do that by using the below command.

DATAENGINER

So this is how you can configure the NTP protocol on your CentOS distribution. This comes in pretty handy because the internal clocks in the systems can sometimes cause issues that may result in inconsistent time problems. Hope you liked the article.

Install Chrony On CentOS 8 / CentOS 7 & RHEL 8 / RHEL 7

There are chances your server already has Chrony installed and configured as a client to use remote clock server(s).

yum install -y chrony

DATAENGINER

Install Chrony Package

Configure NTP Server Using Chrony

In this section, we will configure the servers as an NTP server, which will act as a remote time server for all clients in your organization.

Change the subnet value of directive as per your requirement to allow the clients from your organization network. In my case, clients who have IP addresses from to are allowed to connect to the NTP server for time synchronization.

Restart the Chrony service to apply the configuration change.

Enable Chrony service on system startup.

Add the firewall rules to allow NTP requests from clients.

firewall-cmd —permanent —add-service=ntp

firewall-cmd —reload

Once you have configured the NTP server, go to the client machine and add this server as an NTP server.

Then, run the below command to check how many clients are accessing the NTP server.

DATAENGINER

Configure NTP Client Using Chrony

Install the Chrony package if the package is not already installed.

Now, we will configure this machine as an NTP client, which will reach the NTP server we configured earlier for time synchronization.

Comment out the existing server directives and add a new server directive for our NTP server.

DATAENGINER

Then, restart the Chrony service.

Check the time source to ensure the client is reaching to correct NTP server.

DATAENGINER

By default, NTP client will perform a time synchronization every 64 seconds. However, you can adjust the clock manually without waiting for the next time sync polling.

SYNOPSIS

DATAENGINER

How to Check If Client machine is sync with NTP Server

You can simply run ntpdate command in your Linux Command Line interface and check whether your client machine is getting synced with any of the NTP Server. As you can see from the output as of now there is no NTP Server configured.

How to Test Connection to a NTP Server

If you want to test connection to a NTP Server then you need to use -q option with ntpdate command as shown below. In this example we are testing connection with pool.ntp.org NTP Server using ntpdate -q pool.ntp.org.

Query only — don’t set the clock. More on ntpdate command Page.

It denotes the level in timing hierarchy. Stratum 1 denotes the first level which synchronize its time with external NTP Server. Stratum 2 denotes the second level which synchronizes its time with Stratum 1 servers and so on.

: It is the difference in time between reference or configured NTP Server and the local server. Greater value indicates lesser synchronization with the source.

It denotes the round trip time or latency with the NTP Server.

How to divert Connection output to the System Logs

If you are ever running ntpdate command in cron scripts or in any other bash script then you can always use -s option to divert the command output to Syslog.

Divert logging output from the standard output (default) to the system syslog facility.

How to Synchronize Connection to a NTP Server

If you want to synchronize your time with some hosts lying behind a firewall then you need to use -u option to always use the unprivileged ports. In this example we are trying to sync time with pool.ntp.org using ntpdate -u pool.ntp.org command as shown below.

Direct ntpdate to use an unprivileged port for outgoing packets.

How to Enable Debugging Mode

To enable debugging mode you need to use -d option with ntpdate command as shown in below example. In this example we are trying to debug the time sync with NTP Server pool.ntp.org using ntpdate -d pool.ntp.org command as shown below.

Enable the debugging mode. More on ntpdate command Page.

How to Use Verbose Mode with ntpdate command in Linux

To enable the verbose mode with ntpdate command you need to use -v option as shown below. This option will make all ntpdate tasks visible on console output.

Be verbose. More on ntpdate command Page.

How to Force Step up the time rather than adjust Using ntpdate command

If you want to stepped up the time sync then you need to use -b option as shown below. In this example we have stepped the time sync with pool.ntp.org Server by using ntpdate -vb pool.ntp.org command.

Force the time to be stepped using the settimeofday() system call, rather than slewed (default) using the adjtime() system call.

How to Force the Time Sync to always be slewed

If you want sync to always be slewed then you need to use -B option as shown below. In this example we have slewed the time sync with pool.ntp.org Server using ntpdate -vB pool.ntp.org command.

Force the time to always be slewed using the adjtime() system call, even if the measured offset is greater than +-500 ms.

How to Check Man Page of ntpdate command in Linux

If you want to check the man page of ntpdate command then you need to use man ntpdate command as shown below.

Настройка NTP на CentOS 7

Для начала устанавливаем NTP:

yum install ntp ntpdate
chkconfig ntpd on

Устанавливаем часовой пояс (временную зону), которая соответсвует вашей. Например у меня это Москва, создаем символическую ссылку:

Далее необходимо указать сервера, с которыми мы будем синхронизировать время. По умолчанию 3 сервера уже есть, можно оставить их, можно добавить свои. Мы добавим свой:
Открываем файл ntp.conf для редактирования:

Находим в нем строчки:

Перед ними пишем наш ntp сервер:

Время синхронизируется последовательно. Если первый в списке сервер будет по какой то причине не доступен, то обращение идет ко второму и т.д.

Теперь давайте вручную синхронизируем время с нашим сервером:

Если вы получите ошибку вида: the NTP socket is in use, exiting, значит у вас чем то уже используется порт 123. Попробуйте остановить ntpd следующей командой:

service ntpd stop

и еще раз запустите синхронизацию:

Теперь добавляем в автозапуск и запускаем нашу службу автоматической синхронизации времени:

systemctl enable ntpd
systemctl start ntpd

Проверить работу ntp можно командой ntpq -p

На этом все, мы настроили автоматическую синхронизацию времени на CentOS7. Эта статья может быть актуальна практически для любого дистрибутива Unix, не только CentOS 7. Если у Вас остались вопросы — задавайте их в комментариях.

DATAENGINER

Ваш покорный слуга — компьютерщик широкого профиля: системный администратор, вебмастер, интернет-маркетолог и много чего кто. Вместе с Вами, если Вы конечно не против, разовьем из обычного блога крутой технический комплекс.

Оцените статью
Хостинги