Linux下chrony授时监测脚本

2023-05-16

1.背景概述

Linux下基于gpsd+chrony授时,在有些情况下会存在收敛慢或者参考时间选择错误问题,因此需要授时监测脚本进行监测,便于在异常时候发现并处理。

2. gpsd+chrony授时配置方法

2.1 安装chrony

sudo apt-get install chrony
service chrony restart

修改chrony配置文件:/etc/chrony/chrony.conf

# Welcome to the chrony configuration file. See chrony.conf(5) for more
# information about usuable directives.

# This will use (up to):
# - 4 sources from ntp.ubuntu.com which some are ipv6 enabled
# - 2 sources from 2.ubuntu.pool.ntp.org which is ipv6 enabled as well
# - 1 source from [01].ubuntu.pool.ntp.org each (ipv4 only atm)
# This means by default, up to 6 dual-stack and up to 2 additional IPv4-only
# sources will be used.
# At the same time it retains some protection against one of the entries being
# down (compare to just using one of the lines). See (LP: #1754358) for the
# discussion.
#
# About using servers from the NTP Pool Project in general see (LP: #104525).
# Approved by Ubuntu Technical Board on 2011-02-08.
# See http://www.pool.ntp.org/join.html for more information.
#pool ntp.aliyun.com        iburst maxsources 4
#pool 0.ntp.aliyun.com      iburst maxsources 1
#pool 1.ntp.aliyun.com      iburst maxsources 1
#pool 2.ntp.aliyun.com      iburst maxsources 2
#server ntp.aliyun.com       iburst

# This directive specify the location of the file containing ID/key pairs for
# NTP authentication.
keyfile /etc/chrony/chrony.keys

# This directive specify the file into which chronyd will store the rate
# information.
driftfile /var/lib/chrony/chrony.drift

# Uncomment the following line to turn logging on.
#log tracking measurements statistics

refclock PPS /dev/pps0 lock NMEA refid PPS
refclock SHM 0 offset 0.5 delay 0.2 refid NMEA noselect

#refclock PPS /dev/pps0 lock GPSD prefer refid PPS
#refclock SHM 0 offset 0.0 delay 0.2 refid GPSD
# Log files location.
logdir /var/log/chrony

# Stop bad estimates upsetting machine clock.
maxupdateskew 1.0

leapsectz right/UTC
# This directive enables kernel synchronisation (every 11 minutes) of the
# real-time clock. Note that it can’t be used along with the 'rtcfile' directive.
rtcsync

# Step the system clock instead of slewing it if the adjustment is larger than
# one second, but only in the first three clock updates.
makestep 1.0 -1

2.2 安装gpsd

sudo apt-get install gpsd

修改GPSD配置文件:/etc/default/gpsd,其中/dev/ttyTHS1为gps数据输出串口(波特率自动识别)

# Default settings for the gpsd init script and the hotplug wrapper.

# Start the gpsd daemon automatically at boot time
START_DAEMON="true"

# Use USB hotplugging to add new USB devices automatically to the daemon
USBAUTO="true"

# Devices gpsd should collect to at boot time.
# They need to be read/writeable, either by user gpsd or the group dialout.
DEVICES="/dev/ttyTHS1"

# Other options you want to pass to gpsd
GPSD_OPTIONS="-n -G"

开机自动启配置:

sudo systemctl enable gpsd

2.3 查看gpsd是否接收到gps数据

安装完成后执行 cgps –s查看是否有GPS数据安装完成后执行 cgps –s查看是否有GPS数据
在这里插入图片描述
验证授时是否成功
在终端执行watch chronyc sources –v会出现如下图所示结果:
在这里插入图片描述
红色框内的GPSD前有 * 标志表示接收到GPS信号

3. 监测脚本

功能说明:

  • 授时时间差大于1ms,将认为授时异常
  • 参考时间小于2023,将认为授时异常
  • 授时源不是PPS时,将认为授时异常
  • 授时异常时,将重启授时服务(gpsd+chrony)
#!/usr/bin/env python
# coding: utf-8
# author: rui.peng
# date: 2023-03-24

import os
import sys
import time
import socket
import subprocess


def printt(string):
    print('{} {}'.format(time.ctime(), string))
    sys.stdout.flush()


def get_hostname():
    return socket.gethostname()


def get_chrony_sync_server():
    try:
        source = ''
        reftime = 2020
        r = os.popen('chronyc tracking').readlines()
        print('{}'.format(r))
        if len(r) == 13:
            source = r[0].split('(')[-1][:-2]
            if len(r[2].split(' ')) == 10 :
                reftime = int(r[2].split(' ')[9][:-1])
            offset = float(r[3].split()[3])*1e6
            if 'slow' in r[3]:
                offset = -offset
            printt('{} {:.3f}us'.format(source, offset))
        else:
            printt('cmd exe failed!')
    except Exception as e:
        printt(e)
    return source, offset, reftime


def restart_gpsd():
    subprocess.Popen(['sudo', 'service', 'gpsd', 'restart'])
    printt('restart gpsd!')
    time.sleep(5)


def restart_chrony():
    subprocess.Popen(['sudo', 'service', 'chrony', 'restart'])
    printt('restart chrony!')
    time.sleep(60)


if __name__ == '__main__':
    # sleep a while when the server is booting...
#    time.sleep(60)

    hostname = get_hostname()
    printt('I am {}'.format(hostname))

#    while True:
        # server-a: check if gpsd is working. if not, restart it.
    source, offset, reftime = get_chrony_sync_server()
    printt('{} {:.3f}us reftime:{}'.format(source, offset, reftime))
    #if source != 'PPS':
    if offset > 1000 or offset < -1000 or source != 'PPS' or reftime < 2023:
        restart_gpsd()
        restart_chrony()
        #time.sleep(60)
        print('restart gpsd and chrony')

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Linux下chrony授时监测脚本 的相关文章

  • 将数组传递给函数名称冲突

    Specs GNU bash 版本 3 1 17 无法升级 Premise 我一直在摆弄数组 我想知道是否有任何方法可以让函数的本地变量与所述函数外部的数组同名 Example 在下面的示例中 我将尝试显示该问题 Working bin b
  • numpy 未定义符号:PyFPE_jbuf

    我正在尝试使用一百万首歌曲数据集 为此我必须安装 python 表 numpy cython hdf5 numexpr 等 昨天我设法安装了我需要的所有内容 在使用 hdf5 遇到一些麻烦之后 我下载了预编译的二进制包并将它们保存在我的 b
  • 如何在我的 AWS EC2 实例上安装特定字体?

    我有一个在 AWS EC2 Amazon Linux Elastic Beanstalk 实例上运行的 Python 应用程序 该实例需要某些特定字体才能生成输出 并且想知道如何在部署或实例启动过程中安装它们 我的代码在本地计算机 OS X
  • 构建 makefile 依赖/继承树

    如果我解释得不好或者问了一些明显的问题 我很抱歉 但我是 Linux 内核的新手 而且有点深入 我们有一个嵌入式 Linux 系统 它附带一个 文档非常糟糕的 SDK 其中包含数百个文件夹stuff 大多数文件夹包含rules make m
  • 停止服务时单元陷入故障状态(状态=143)[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 这是我的问题 我有 CentOS 和 java 进程在上面运行 Java进程是通过启动 停止脚本来操作的 它也创建了 java 实例的 p
  • 在 LINUX 上使用 Python 连接到 OLAP 多维数据集

    我知道如何在 Windows 上使用 Python 连接到 MS OLAP 多维数据集 嗯 至少有一种方法 通常我使用 win32py 包并调用 COM 对象进行连接 import win32com client connection wi
  • Linux 中热插拔设备时检测设备是否存在

    我正在运行 SPIcode http lxr free electrons com source drivers spi spi omap2 mcspi c在熊猫板上 我想知道其中的哪个功能code http lxr free electr
  • 在Linux中断上下文中运行用户线程

    我正在编写一些定制的应用程序 并允许更改 Linux 内核中的中断处理程序代码 我有一个用户线程正在等待中断发生 如果发生中断 那么我要做的第一件事就是执行该用户线程 有什么办法让它发挥作用吗 Thanks 创建一个字符设备 这就是内核所做
  • 从 TypeScript 运行任何 Linux 终端命令?

    有没有办法直接从 TypeScript 类中执行 Linux 终端命令 这个想法是做类似的事情 let myTerminal new LinuxTerminal let terminalResult myTerminal run sudo
  • 无需 cron 在后台发送邮件

    我想知道是否有一种方法可以运行 PHP 循环 以便在后台向订阅者发送几百封电子邮件 我的目标是格式化新闻通讯 单击发送 然后关闭浏览器或更改页面 当然 发送电子邮件的实际过程将在后台运行 不会因浏览器关闭而中断 我知道这可以通过 cron
  • 如何查找连接到 AF_INET 套接字的客户端的 UID?

    有什么方法或类似的东西ucred for AF UNIX如果是AF INET插座 TCP在我的例子中 找出连接到我的套接字的客户端的UID 还有 proc net tcp但它显示了UID of the creator插座的而不是连接的cli
  • 如何制作和应用SVN补丁?

    我想制作一个SVN类型的补丁文件httpd conf这样我就可以轻松地将其应用到其他主机上 If I do cd root diff Naur etc httpd conf httpd conf original etc httpd con
  • .NET Core 中的跨平台文件名处理

    如何处理文件名System IO以跨平台方式运行类以使其在 Windows 和 Linux 上运行 例如 我编写的代码在 Windows 上完美运行 但它不会在 Ubuntu Linux 上创建文件 var tempFilename Dat
  • 如何模拟ARM处理器运行环境并加载Linux内核模块?

    我尝试加载我的vmlinux into gdb并使用 ARM 内核模拟器 但我不明白为什么我会得到Undefined target command sim 这是外壳输出 arm eabi gdb vmlinux GNU gdb GDB 7
  • ansible 重新启动 2.1.1.0 失败

    我一直在尝试创建一个非常简单的 Ansible 剧本 它将重新启动服务器并等待它回来 我过去在 Ansible 1 9 上有一个可以运行的 但我最近升级到 2 1 1 0 并且失败了 我正在重新启动的主机名为 idm IP 为 192 16
  • Locale.getDefault() 始终返回 en

    unix 机器上的服务器始终使用 en 作为默认区域设置 以下是区域设置输出 LANG en US LC CTYPE C LC NUMERIC C LC TIME C LC COLLATE C LC MONETARY C LC MESSAG
  • 拆分字符串以仅获取前 5 个字符

    我想去那个地点 var log src ap kernelmodule 10 001 100 但看起来我的代码必须处理 ap kernelmodule 10 002 100 ap kernelmodule 10 003 101 等 我想使用
  • 修改linux下的路径

    虽然我认为我已经接近 Linux 专业人士 但显然我仍然是一个初学者 当我登录服务器时 我需要使用最新版本的R 统计软件 R 安装在 2 个地方 当我运行以下命令时 which R I get usr bin R 进而 R version
  • bluetoothctl 到 hcitool 等效命令

    在 Linux 中 我曾经使用 hidd connect mmac 来连接 BT 设备 但自 Bluez5 以来 这种情况已经消失了 我可以使用 bluetoothctl 手动建立连接 但我需要从我的应用程序使用这些命令 并且使用 blue
  • 从 PL/SQL 调用 shell 脚本,但 shell 以 grid 用户而非 oracle 身份执行

    我正在尝试使用 Runtime getRuntime exec 从 Oracle 数据库内部执行 shell 脚本 在 Red Hat 5 5 上运行的 Oracle 11 2 0 4 EE CREATE OR REPLACE proced

随机推荐

  • 策略模式

    策略模式 由于最近在研究学习设计模式 xff0c 我会用自己的理解方式来表述对设计模式的学习和认识 xff0c 通过最常用 好记的案例来记住和使用设计模式 xff0c 希望对设计代码方面有所提高和改进 一 应用背景 在软件开发中常常遇到这种
  • Vs2010与VC的区别

    VS2010与VC 43 43 编译器的区别 xff1a 1 VS2010并不是针对C 43 43 的 xff0c C 43 43 只是它的一小部分 xff0c 它更加关注 net平台程序开发 xff08 主要是C VB xff0c C 4
  • 通过OAuth2.0方式弹出授权页面获得用户基本信息

    获取微信用户的个人的信息的时候 xff0c 要特别注意的是有两个不同的Access Token xff0c 他们产生的方式不一样 xff0c 一种是使用AppID和AppSecret获取的access token xff0c 一种是OAut
  • SqlSugar入门级教程+实例 (.net core下的)

    官方参考 xff1a http www codeisbug com Doc 8 前言 xff1a 这应该是目前最好用的ORM框架之一了 xff0c 而且支持 net core xff0c 网上除了官方文档其他参考就少了点 xff0c 自己整
  • c#通过串口及CAN模块实现上位及下位机通讯

    目录 前言 一 串口 CAN总线 二 使用步骤 1 RS232串口通讯 xff08 指令下发与接收 xff09 2 CAN总线通讯 总结 前言 学习及工作中我们经常会遇到上位机与下位机通讯等工作 xff0c 结合场景使用不同的通讯方式实时通
  • C# String转int主要有四种方法

    String转int主要有四种方法 1 int Parse 是一种类容转换 xff1b 表示将数字内容的字符串转为int类型 如果字符串为空 xff0c 则抛出ArgumentNullException异常 xff1b 如果字符串内容不是数
  • 基于正点原子STM32F103精英板IIC实验的MS5611气压计的使用

    MS5611是一款气压计 xff0c 能够提供高精度的气压值与温度值 xff0c 这次做项目正好需要用到这款传感器 xff0c 包括之前也没好好学习用过IIC xff0c 所以写下博客记录一下 如果有需要使用的朋友可以去https down
  • 关于C#使用XMLDocument生成XML文档时,UTF-8编码的BOM问题

    XmlSerializer 的序列化 默认指定 编码 xmlWriterSettings Encoding 61 Encoding UTF8 这种编码是带bom标记位 BOM byte order mark 字节顺序标记 的 改为 xff1
  • Winform datagridview中显示下拉框示例

    方式一 xff1a 如下图所示 xff0c 该方式也是较为简单的一种 你只需要添加一列类型为DataGridViewComboBoxColumn的列 xff0c 然后添加数据源即可 但是我们看到这种方式的下拉列表看起来并不是十分的美观 xf
  • subject may not be empty[Git]

    PS D MySource sino manager gt git commit husky gt pre commit node v10 15 3 STARTED Preparing SUCCESS Preparing STARTED R
  • [转]C# HTTP 错误 403.14 - Forbidden Web

    HTTP 错误 403 14 ForbiddenWeb 服务器被配置为不列出此目录的内容 出现以上这个错误可能有如下解决方法 xff1a 1 将应用程序池设置成V4 0 2 在配置文件中加上以下几句代码 xff1a lt system we
  • c# 创建Web Api项目

    创建WebApi项目 xff1a 在VS工具中创建一个ASP NET Web应用程序 选择Webapi 一个webapi项目就创建好了 这里简单的写一个post和get两种请求的方法 xff0c 由于post请求参数需要参数体的形式 xff
  • C# 反射获取类的成员变量名称及值

    测试用的类 public class PersonData public string gender 61 string Empty public List lt int gt pifuRGB 61 new List lt int gt 0
  • cstring转换为char*

    在Visual C 43 43 NET2005中 xff0c 默认的字符集形式是Unicode xff0c 但在VC6 0等工程中 xff0c 默认的字符集形式是多字节字符集 xff08 MBCS xff1a Multi Byte Char
  • Error creating bean with name 'userController'

    Caused by org springframework beans factory UnsatisfiedDependencyException Error creating bean with name 39 userControll
  • IntelliJ IDEA Cannot find declaration to go to

    最近在用IntelliJ IDEA开发一个微服务的项目的时候 xff0c 从git clone了代码 xff0c 再用IntelliJ IDEA导入项目以后 项目里好多方法 类和属性都无法转到定义或者声明处 xff0c 无论是Ctrl 43
  • CString转char * ,string

    CString头文件 include lt afx h gt string头文件 include lt string h gt 1 CString转char CString cstr char p 61 LPSTR LPCTSTR cstr
  • GPS数据包格式+数据解析

    GPS数据包格式 43 数据解析 一 全球时区的划分 xff1a 每个时区跨15 经度 以0 经线为界向东向西各划出7 5 经度 xff0c 作为0时区 即0时区的经度范围是7 5 W 7 5 E 从7 5 E与7 5 W分别向东 向西每1
  • 在C#中使用libcurl库

    几乎在所有的linux发行版中 xff0c 默认都是包含有libcurl库的 那么 xff0c libcurl是使用C开发的 xff0c 自然 xff0c 当你用C或C 43 43 使用libcurl库的时候很方便 但是 xff0c 如果你
  • Linux下chrony授时监测脚本

    1 背景概述 Linux下基于gpsd 43 chrony授时 xff0c 在有些情况下会存在收敛慢或者参考时间选择错误问题 xff0c 因此需要授时监测脚本进行监测 xff0c 便于在异常时候发现并处理 2 gpsd 43 chrony授