Python 使用ntplib库同步校准当地时间的方法 (NTP)

NTP(Network Time Protocol)是由美国德拉瓦大学的David L. Mills教授于1985年提出,设计用来在Internet上使不同的机器能维持相同时间的一种通讯协定。

 

NTP估算封包在网络上的往返延迟,独立地估算计算机时钟偏差,从而实现在网络上的高精准度计算机校时。

NTP服务在Linux系统比较常见,其实Python也一样,可网上搜索"python获取时间"时,很多是解析页面获取时间的笨办法,殊不知Python也可使用NTP服务进行时间同步获取精确时间、只需要使用ntplib库即可实现。

 

ntplib库用法简介

安装ntplib:

easy_install ntplib

pip install ntplib

代码解释:

import os 
import time 
import ntplib 



c = ntplib.NTPClient() 
response = c.request('pool.ntp.org') 

ts = response.tx_time 

_date = time.strftime('%Y-%m-%d',time.localtime(ts)) 
_time = time.strftime('%X',time.localtime(ts)) 

os.system('date {} && time {}'.format(_date,_time)) 

 

源码实例:

#用于检查时间偏移的函数
def check_time(self):
    #确保我们的蜜罐时间是一致的,与实际时间相差不太远。

    poll = self.config['timecheck']['poll']
    ntp_poll = self.config['timecheck']['ntp_pool']
    while True:
        clnt = ntplib.NTPClient()
        try:
            response = clnt.request(ntp_poll, version=3)
            diff = response.offset
            if abs(diff) >= 15:
                logger.error('Timings found to be far off, shutting down drone ({0})'.format(diff))
                sys.exit(1)
            else:
                logger.debug('Polled ntp server and found that drone has {0} seconds offset.'.format(diff))
        except (ntplib.NTPException, _socket.error) as ex:
            logger.warning('Error while polling ntp server: {0}'.format(ex))
        gevent.sleep(poll * 60 * 60)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

墨痕诉清风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值