当前位置: 首页>>代码示例>>Python>>正文


Python ntplib.NTPClient方法代码示例

本文整理汇总了Python中ntplib.NTPClient方法的典型用法代码示例。如果您正苦于以下问题:Python ntplib.NTPClient方法的具体用法?Python ntplib.NTPClient怎么用?Python ntplib.NTPClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ntplib的用法示例。


在下文中一共展示了ntplib.NTPClient方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SyncClockToNtp

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def SyncClockToNtp(retries: int = 2, server: Text = 'time.google.com'):
  """Syncs the hardware clock to an NTP server."""
  logging.info('Reading time from NTP server %s.', server)

  attempts = 0
  client = ntplib.NTPClient()
  response = None

  while True:
    try:
      response = client.request(server, version=3)
    except (ntplib.NTPException, socket.gaierror) as e:
      logging.error('NTP client request error: %s', str(e))
    if response or attempts >= retries:
      break
    logging.info(
        'Unable to contact NTP server %s to sync machine clock.  This '
        'machine may not have an IP address yet; waiting %d seconds and '
        'trying again. Repeated failure may indicate network or driver '
        'problems.', server, RETRY_DELAY)
    time.sleep(RETRY_DELAY)
    attempts += 1

  if not response:
    raise NtpException('No response from NTP server.')

  local_time = time.localtime(response.ref_time)
  current_date = time.strftime('%m-%d-%Y', local_time)
  current_time = time.strftime('%H:%M:%S', local_time)
  logging.info('Current date/time is %s %s', current_date, current_time)

  date_set = r'%s\cmd.exe /c date %s' % (WINPE_SYSTEM32, current_date)
  result = subprocess.call(date_set, shell=True)
  logging.info('Setting date returned result %s', result)
  time_set = r'%s\cmd.exe /c time %s' % (WINPE_SYSTEM32, current_time)
  result = subprocess.call(time_set, shell=True)
  logging.info('Setting time returned result %s', result) 
开发者ID:google,项目名称:glazier,代码行数:39,代码来源:ntp.py

示例2: autoSynchroTime

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def autoSynchroTime():
    """
    同步北京时间,执行时候,请务必用sudo,sudo,sudo 执行,否则会报权限错误,windows打开ide或者cmd请用管理员身份
    :return:
    """
    c = ntplib.NTPClient()

    hosts = ['ntp1.aliyun.com', 'ntp2.aliyun.com', 'ntp3.aliyun.com', 'ntp4.aliyun.com', 'cn.pool.ntp.org']

    print(u"正在同步时间,请耐心等待30秒左右,如果下面有错误发送,可以忽略!!")
    print(u"系统当前时间{}".format(str(datetime.datetime.now())[:22]))
    system = platform.system()
    if system == "Windows":  # windows 同步时间未测试过,参考地址:https://www.jianshu.com/p/92ec15da6cc3
        for host in hosts:
            os.popen('w32tm /register')
            os.popen('net start w32time')
            os.popen('w32tm /config /manualpeerlist:"{}" /syncfromflags:manual /reliable:yes /update'.format(host))
            os.popen('ping -n 3 127.0.0.1 >nul')
            sin = os.popen('w32tm /resync')
            if sin is 0:
                break
    else:  # mac同步地址,如果ntpdate未安装,brew install ntpdate    linux 安装 yum install -y ntpdate
        for host in hosts:
            sin = os.popen('ntpdate {}'.format(host))
            if sin is 0:
                break
    print(u"同步后时间:{}".format(str(datetime.datetime.now())[:22])) 
开发者ID:testerSunshine,项目名称:12306,代码行数:29,代码来源:AutoSynchroTime.py

示例3: get_network_time

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def get_network_time():
    start = time.time()
    c = ntplib.NTPClient()
    response = c.request('pool.ntp.org')
    ts = response.tx_time
    return ts 
开发者ID:Emptyset110,项目名称:SinaL2,代码行数:8,代码来源:util.py

示例4: get_ntp_response

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def get_ntp_response():
    for retry in range(NTP_RETRIES):
        ntp_server = config.user.ntp_servers[retry % len(config.user.ntp_servers)]
        try:
            ntp_client = NTPClient()
            response = ntp_client.request(ntp_server, version=NTP_VERSION, timeout=config.user.ntp_request_timeout)
        except Exception as e:
            logger.warning(e)
            continue
        return response

    # FIXME: Provide some proper clean before exiting
    logger.fatal("Could not contact NTP servers after %d retries", NTP_RETRIES)
    sys.exit(-1) 
开发者ID:theQRL,项目名称:QRL,代码行数:16,代码来源:ntp.py

示例5: print_time

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def print_time():
    ntp_client = ntplib.NTPClient()
    response = ntp_client.request('pool.ntp.org')
    print (ctime(response.tx_time)) 
开发者ID:PacktPublishing,项目名称:Python-Network-Programming-Cookbook-Second-Edition,代码行数:6,代码来源:1_11_print_machine_time.py

示例6: main

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def main(address, v):
    c = ntplib.NTPClient()
    response = c.request(address, version=v)
    print("Response Offset: ", response.offset)
    print("Version: ", response.version)
    print("Response (Time): ", ctime(response.tx_time))
    print("Leap: ", ntplib.leap_to_text(response.leap))
    print("Root Delay: ", response.root_delay)
    print(ntplib.ref_id_to_text(response.ref_id)) 
开发者ID:PacktPublishing,项目名称:Python-Network-Programming-Cookbook-Second-Edition,代码行数:11,代码来源:11_5_query_ntp_server.py

示例7: __init__

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def __init__(self, *args, **kwargs):
        """
        @option options [Integer] interval (30) the time interval in seconds
            for OTP This defaults to 30 which is standard.
        """
        self.interval = kwargs.pop('interval', 30)
        if self.systime_offset is None:
            try:
                c = ntplib.NTPClient()
                TOTP.systime_offset = int(c.request(
                    'pool.ntp.org', version=3).offset)
            except Exception:
                self.systime_offset = 0
        super(TOTP, self).__init__(*args, **kwargs) 
开发者ID:projectarkc,项目名称:arkc-client,代码行数:16,代码来源:totp.py

示例8: get_ntp_worker

# 需要导入模块: import ntplib [as 别名]
# 或者: from ntplib import NTPClient [as 别名]
def get_ntp_worker(server):
    try:
        client = ntplib.NTPClient()
        response = client.request(server, version=3)
        ntp = response.tx_time
        return ntp
    except Exception as e:
        return None 
开发者ID:StorjOld,项目名称:pyp2p,代码行数:10,代码来源:lib.py


注:本文中的ntplib.NTPClient方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。