async def exact_time(): host = app.config['NTP_SERVER'] port = app.config['NTP_PORT'] stream = await asyncio_dgram.connect((host, port)) ntp_request = ExactTimeService.create_ntp_request_data() await stream.send(ntp_request) response_data, remote_addr = await stream.recv() stream.close() ntp_stats = ExactTimeService.get_ntp_stats(response_data) struct_time = localtime(ntp_stats.tx_time) result = { 'host': host, 'offset': ntp_stats.offset, 'date': strftime('%Y.%m.%d', struct_time), 'time': strftime('%H:%M:%S', struct_time), 'zone': strftime('%z', struct_time), 'full_time': strftime('%Y.%m.%d %H:%M:%S %z', struct_time), 'ref_id': ntp.ref_id_to_text(ntp_stats.ref_id), } return result
def check_time(): client = ntplib.NTPClient() rsps = client.request('asia.pool.ntp.org', version=3) print('Server:', ntplib.ref_id_to_text(rsps.ref_id)) print('Offset:', rsps.offset) print('Time:', format_ts(rsps.tx_time))
def ntp_request(host: str) -> Union[None, NTPResponse]: """ Request NTP server host to retrieve attributes """ try: socket.getaddrinfo(host, "ntp") except socket.gaierror as error: sys.stderr.write("Cannot resolve host '{}': {}\n".format(host, error)) sys.stderr.flush() return None client = ntplib.NTPClient() attrs = {} try: response = client.request(host) for attr in [ "offset", "delay", "root_delay", "leap", "version", "stratum", "mode", "ref_id", ]: attrs[attr] = getattr(response, attr) attrs["ref_id"] = ref_id_to_text(attrs["ref_id"], attrs["stratum"]) except NTPException as error: sys.stderr.write("Cannot convert reference: {}\n".format(error)) sys.stderr.flush() return None return NTPResponse(host, **attrs)
def clock_state(): """ Determine the state of the system clock and return a hash of information conforming to the definition of a SystemClockStatus object as described in the JSON dictionary. time - Current system time as an ISO 8601 string synchronized - Whether or not the clock is synchronized to an outside source. source - The source of synchronization. Currently, the only valid value is "ntp." Not provided if not synchronized. reference - A human-readable string describing the source. Not provided if not synchronized. offset - A float indicating the estimated clock offset. Not provided if not synchronized. error - """ adjtime = ntp_adjtime() system_synchronized = adjtime.synchronized # Format the local time with offset as ISO 8601. Python's # strftime() only does "-0400" format; we need "-04:00". utc = datetime.datetime.utcnow() local_tz = tzlocal.get_localzone() time_here = pytz.utc.localize(utc).astimezone(local_tz) raw_offset = time_here.strftime("%z") if len(raw_offset): offset = raw_offset[:3] + ":" + raw_offset[-2:] else: offset = "" result = { "time": time_here.strftime("%Y-%m-%dT%H:%M:%S.%f") + offset, "synchronized": system_synchronized } if system_synchronized: # Assume NTP for the time being try: ntp = ntplib.NTPClient().request("127.0.0.1") result["offset"] = ntp.offset result["source"] = "ntp" result["reference"] = "%s from %s" % (ntplib.stratum_to_text( ntp.stratum), ntplib.ref_id_to_text(ntp.ref_id)) except Exception as ex: result["synchronized"] = False result["error"] = str(ex) return result
def clock_state(): """ Determine the state of the system clock and return a hash of information conforming to the definition of a SystemClockStatus object as described in the JSON dictionary. time - Current system time as an ISO 8601 string synchronized - Whether or not the clock is synchronized to an outside source. source - The source of synchronization. Currently, the only valid value is "ntp." Not provided if not synchronized. reference - A human-readable string describing the source. Not provided if not synchronized. offset - A float indicating the estimated clock offset. Not provided if not synchronized. error - """ adjtime = ntp_adjtime() system_synchronized = adjtime.synchronized # Format the local time with offset as ISO 8601. Python's # strftime() only does "-0400" format; we need "-04:00". utc = datetime.datetime.utcnow() local_tz = tzlocal.get_localzone() time_here = pytz.utc.localize(utc).astimezone(local_tz) raw_offset = time_here.strftime("%z") if len(raw_offset): offset = raw_offset[:3] + ":" + raw_offset[-2:] else: offset = "" result = {"time": time_here.strftime("%Y-%m-%dT%H:%M:%S.%f") + offset, "synchronized": system_synchronized} if system_synchronized: # Assume NTP for the time being try: ntp = ntplib.NTPClient().request("127.0.0.1") result["offset"] = ntp.offset result["source"] = "ntp" result["reference"] = "%s from %s" % ( ntplib.stratum_to_text(ntp.stratum), ntplib.ref_id_to_text(ntp.ref_id), ) except Exception as ex: result["error"] = str(ex) return result
def query_detail(self, response): if response: offset = response.offset refid = ntplib.ref_id_to_text(response.ref_id) rdelay = response.root_delay else: offset = refid = rdelay = None return offset, refid, rdelay
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))
def get_status(self, talker="NT", hostname="127.0.0.1", flag_proprietary=True): """Query a NTP server to get the status of time FIX: I do not like that I save a string into self.params """ params = {} client = ntplib.NTPClient() timestamp1 = time.time() response = client.request(hostname) # , version=4) timestamp2 = time.time() if flag_proprietary and talker[0] != "P": talker = "P" + talker params["talker"] = talker params["timestamp"] = (timestamp1 + timestamp2) / 2.0 params["host"] = hostname # Must be IP4 ip address params["ref_clock"] = ntplib.ref_id_to_text(response.ref_id, response.stratum) params["stratum"] = response.stratum params["last_update"] = response.ref_time params["offset"] = "%f" % response.offset params["precision"] = response.precision params["root_delay"] = "%.6f" % response.root_delay params["root_dispersion"] = "%.6f" % response.root_dispersion # nmea_str = '${talker}ZNT,{timestamp},{host},{ref_clock},{stratum},{last_update},' # nmea_str += '{offset},{precision},{root_delay},{root_dispersion}' # nmea_str = nmea_str.format(**params) fields = [] for key in ( "timestamp", "host", "ref_clock", "stratum", "last_update", "offset", "precision", "root_delay", "root_dispersion", ): fields.append(str(params[key])) nmea_str = "$" + talker + "ZNT," + ",".join(fields) checksum = checksum_str(nmea_str) nmea_str += "*" + checksum self.nmea_str = nmea_str self.params = params try: match = znt_regex.search(nmea_str).groupdict() except: print "results are wrong???" print_response(response) return nmea_str
def ntp_logging(): ''' Compute a timestamp using NIST Internet Time Servers as an additional level of assurance for database. This function is called by search function or can be called via XML or JSON remote procedure calls. Example for XMLRPC: >>> from xmlrpclib import ServerProxy >>> s = ServerProxy('http://ml-lab.bioinformatics.org/init/plugin_notalogger/call/xmlrpc') >>> s.ntp_logging() ''' ntp_pool = ['asia.pool.ntp.org', 'europe.pool.ntp.org', 'oceania.pool.ntp.org', 'north-america.pool.ntp.org', 'south-america.pool.ntp.org', 'africa.pool.ntp.org'] client = ntplib.NTPClient() server = random.choice(ntp_pool) response = client.request(server, version=3) try: results = ['Network time server: ' + server, 'Offset : %f' % response.offset, 'Stratum : %s (%d)' % (ntplib.stratum_to_text(response.stratum), response.stratum), 'Precision : %d' % response.precision, 'Root delay : %f ' % response.root_delay, 'Root dispersion : %f' % response.root_dispersion, 'Delay : %f' % response.delay, 'Leap indicator : %s (%d)' % (ntplib.leap_to_text(response.leap), response.leap), 'Poll : %d' % response.poll, 'Mode : %s (%d)' % (ntplib.mode_to_text(response.mode), response.mode), 'Reference clock identifier : ' + \ ntplib.ref_id_to_text(response.ref_id, response.stratum), 'Original timestamp : ' + time.ctime(response.orig_time), 'Receive timestamp : ' + time.ctime(response.recv_time), 'Transmit timestamp : ' + time.ctime(response.tx_time), 'Destination timestamp : ' + time.ctime(response.dest_time)] results = ' | '.join(results) except: results = 'Failure to connect to network time server or there is \ an internet error. Please try again later.' notalogger_db.logger.insert(notarizecode='', name='', pidentifier='', email='', usage='NTP pool server time check', comments=results, datetimeserver=str(server), seconds_since_epoch=str(time.time())) notalogger_db.commit()
def ntp_stamp(): if session.username == None: redirect(URL(r=request, f='../account/log_in')) form = FORM( TABLE( TR('Network Time Servers: ', SELECT('asia.pool.ntp.org', 'europe.pool.ntp.org', 'oceania.pool.ntp.org', 'north-america.pool.ntp.org', 'south-america.pool.ntp.org', 'africa-america.pool.ntp.org', _name='server')), TR(INPUT(_type='submit', _value='Stamp')))) if form.accepts(request.vars, session): from time import ctime import ntplib client = ntplib.NTPClient() try: response = client.request(form.vars.server, version=3) results = ['Network time server: ' + form.vars.server, 'Offset : %f' % response.offset, 'Stratum : %s (%d)' % (ntplib.stratum_to_text(response.stratum), response.stratum), 'Precision : %d' % response.precision, 'Root delay : %f ' % response.root_delay, 'Root dispersion : %f' % response.root_dispersion, 'Delay : %f' % response.delay, 'Leap indicator : %s (%d)' % (ntplib.leap_to_text(response.leap), response.leap), 'Poll : %d' % response.poll, 'Mode : %s (%d)' % (ntplib.mode_to_text(response.mode), response.mode), 'Reference clock identifier : ' + \ ntplib.ref_id_to_text(response.ref_id, response.stratum), 'Original timestamp : ' + ctime(response.orig_time), 'Receive timestamp : ' + ctime(response.recv_time), 'Transmit timestamp : ' + ctime(response.tx_time), 'Destination timestamp : ' + ctime(response.dest_time)] db.log.insert(event='NTP timestamp. ' + ' | '.join(results), user=session.username) db.user_event.insert(event='NTP timestamp. ' + ' | '.join(results), user=session.username) db.entry_hash.insert(eid='NTP', edatetime='NTP', etitle='NTP', ehash='NTP timestamp. ' + ' | '.join(results)) db.comment_hash.insert(cid='NTP', cdatetime='NTP', eid='NTP', chash='NTP timestamp. ' + ' | '.join(results)) except: results = 'Failure to connect to network time server or there is \ an internet error. Please try again later.' session.result = results redirect(URL(r=request, f='ntp_stamp_output')) return dict(form=form)
def stats(): response = get_data() return { "time": asctime(gmtime(response.tx_time)), "offset": response.offset, "leap": ntplib.leap_to_text(response.leap), "delay": response.root_delay, "ref": ntplib.ref_id_to_text(response.ref_id), "stratum": ntplib.stratum_to_text(response.stratum), "timestamp": response.tx_time }
def main(): #sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #sock.sendto("hello!", ("127.0.0.1", 1234)) c = ntplib.NTPClient() rep = c.request("localhost", port=16384) rep = c.request("pool.ntp.org") print "version", rep.version print "offset", rep.offset print "root_delay", rep.root_delay print "ref_id", rep.ref_id print "ref_id text", ntplib.ref_id_to_text(rep.ref_id) print "tx_time", rep.tx_time, time.time() print "ctime", time.ctime(rep.tx_time)
def get_status(self, talker='NT', hostname='127.0.0.1', flag_proprietary=True): '''Query a NTP server to get the status of time FIX: I do not like that I save a string into self.params ''' params = {} client = ntplib.NTPClient() timestamp1 = time.time() response = client.request(hostname) #, version=4) timestamp2 = time.time() if flag_proprietary and talker[0] != 'P': talker = 'P' + talker params['talker'] = talker params['timestamp'] = (timestamp1 + timestamp2) / 2. params['host'] = hostname # Must be IP4 ip address params['ref_clock'] = ntplib.ref_id_to_text(response.ref_id, response.stratum) params['stratum'] = response.stratum params['last_update'] = response.ref_time params['offset'] = '%f' % response.offset params['precision'] = response.precision params['root_delay'] = '%.6f' % response.root_delay params['root_dispersion'] = '%.6f' % response.root_dispersion #nmea_str = '${talker}ZNT,{timestamp},{host},{ref_clock},{stratum},{last_update},' #nmea_str += '{offset},{precision},{root_delay},{root_dispersion}' #nmea_str = nmea_str.format(**params) fields = [] for key in ('timestamp', 'host', 'ref_clock', 'stratum', 'last_update', 'offset', 'precision', 'root_delay', 'root_dispersion'): fields.append(str(params[key])) nmea_str = '$' + talker + 'ZNT,' + ','.join(fields) checksum = checksum_str(nmea_str) nmea_str += '*' + checksum self.nmea_str = nmea_str self.params = params try: match = znt_regex.search(nmea_str).groupdict() except: print 'results are wrong???' print_response(response) return nmea_str
def test_helpers(self): """Helper methods tests.""" client = ntplib.NTPClient() time.sleep(self.POLL_DELAY) info = client.request(self.NTP_SERVER) self.assertEqual(int(info.tx_time), ntplib.ntp_to_system_time( ntplib.system_to_ntp_time(int(info.tx_time)))) self.assertTrue(isinstance(ntplib.leap_to_text(info.leap), str)) self.assertTrue(isinstance(ntplib.mode_to_text(info.mode), str)) self.assertTrue(isinstance(ntplib.stratum_to_text(info.stratum), str)) self.assertTrue(isinstance(ntplib.ref_id_to_text(info.ref_id, info.stratum), str))
def test_helpers(self): """Helper methods tests.""" client = ntplib.NTPClient() time.sleep(self.POLL_DELAY) info = client.request(self.NTP_SERVER) self.assertEqual( int(info.tx_time), ntplib.ntp_to_system_time( ntplib.system_to_ntp_time(int(info.tx_time)))) self.assertTrue(isinstance(ntplib.leap_to_text(info.leap), str)) self.assertTrue(isinstance(ntplib.mode_to_text(info.mode), str)) self.assertTrue(isinstance(ntplib.stratum_to_text(info.stratum), str)) self.assertTrue( isinstance(ntplib.ref_id_to_text(info.ref_id, info.stratum), str))
def print_response(response): print ("Version number : %d" % response.version) print ("Offset : %f" % response.offset) print ("Stratum : %s (%d)" % (ntplib.stratum_to_text(response.stratum), response.stratum)) print ("Precision : %d" % response.precision) print ("Root delay : %f " % response.root_delay) print ("Root dispersion : %f" % response.root_dispersion) print ("Delay : %f" % response.delay) print ("Leap indicator : %s (%d)" % (ntplib.leap_to_text(response.leap), response.leap)) print ("Poll : %d" % response.poll) print ("Mode : %s (%d)" % (ntplib.mode_to_text(response.mode), response.mode)) print ("Python time: %f, %s" % (time.time(), str(datetime.datetime.utcnow()))) print ("Transmit timestamp : " + time.ctime(response.tx_time)) print ("Reference timestamp : " + time.ctime(response.ref_time)) print ("Original timestamp : " + time.ctime(response.orig_time)) print ("Receive timestamp : " + time.ctime(response.recv_time)) print ("Destination timestamp : " + time.ctime(response.dest_time)) print ("Reference clock identifier : " + ntplib.ref_id_to_text(response.ref_id, response.stratum))
def get_status(self, talker='NT', hostname='127.0.0.1', flag_proprietary=True): """Query a NTP server to get the status of time TODO(schwehr): I do not like that I save a string into self.params """ params = {} client = ntplib.NTPClient() timestamp1 = time.time() response = client.request(hostname) #, version=4) timestamp2 = time.time() if flag_proprietary and talker[0] != 'P': talker = 'P' + talker params['talker'] = talker params['timestamp'] = (timestamp1 + timestamp2) /2. params['host'] = hostname # Must be IP4 ip address params['ref_clock'] = ntplib.ref_id_to_text(response.ref_id, response.stratum) params['stratum'] = response.stratum params['last_update'] = response.ref_time params['offset'] = '%f' % response.offset params['precision'] = response.precision params['root_delay'] = '%.6f' % response.root_delay params['root_dispersion'] = '%.6f' % response.root_dispersion fields = [] for key in ('timestamp', 'host', 'ref_clock', 'stratum', 'last_update', 'offset','precision','root_delay','root_dispersion'): fields.append(str(params[key])) nmea_str = '$' + talker + 'ZNT,' + ','.join(fields) checksum = checksum_str(nmea_str) nmea_str += '*' + checksum self.nmea_str = nmea_str self.params = params try: match = znt_regex.search(nmea_str).groupdict() except: print 'Results are wrong?' print_response(response) return nmea_str
def print_response(response): print('Version number : %d' % response.version) print('Offset : %f' % response.offset) print('Stratum : %s (%d)' % (ntplib.stratum_to_text(response.stratum), response.stratum)) print('Precision : %d' % response.precision) print('Root delay : %f ' % response.root_delay) print('Root dispersion : %f' % response.root_dispersion) print('Delay : %f' % response.delay) print('Leap indicator : %s (%d)' % (ntplib.leap_to_text(response.leap), response.leap)) print('Poll : %d' % response.poll) print('Mode : %s (%d)' % (ntplib.mode_to_text(response.mode), response.mode)) print('Python time: %f, %s' % (time.time(), str(datetime.datetime.utcnow()))) print('Transmit timestamp : ' + time.ctime(response.tx_time)) print('Reference timestamp : ' + time.ctime(response.ref_time)) print('Original timestamp : ' + time.ctime(response.orig_time)) print('Receive timestamp : ' + time.ctime(response.recv_time)) print('Destination timestamp : ' + time.ctime(response.dest_time)) print('Reference clock identifier : ' + ntplib.ref_id_to_text(response.ref_id, response.stratum))
def doRun(self): c = ntplib.NTPClient() response = c.request('time.google.com', version=3) self.print_view(response.offset) self.print_view(response.version) self.print_view("서버시간:", ctime(response.tx_time)) self.print_view("시스템시간:", ctime(time.time())) neolib4Win._win_set_time( datetime.datetime.fromtimestamp(int(response.tx_time + response.root_delay)).timetuple()) self.print_view("시스템시간:", ctime(time.time())) self.print_view(response.tx_time - time.time()) self.print_view(ntplib.leap_to_text(response.leap)) self.print_view(response.root_delay) self.print_view(ntplib.ref_id_to_text(response.ref_id))
if len(sys.argv) > 1: hostname = sys.argv[1] else: sys.stdout.write('NTP server ? ') hostname = sys.stdin.readline().strip() client = ntplib.NTPClient() response = client.request(hostname, version=3) print('Version number : %d' % response.version) print('Offset : %f' % response.offset) print('Stratum : %s (%d)' % (ntplib.stratum_to_text(response.stratum), response.stratum)) print('Precision : %d' % response.precision) print('Root delay : %f ' % response.root_delay) print('Root dispersion : %f' % response.root_dispersion) print('Delay : %f' % response.delay) print('Leap indicator : %s (%d)' % (ntplib.leap_to_text(response.leap), response.leap)) print('Poll : %d' % response.poll) print('Mode : %s (%d)' % (ntplib.mode_to_text(response.mode), response.mode)) print('Transmit timestamp : ' + str(response.tx_time)) print('Reference timestamp : ' + str(response.ref_time)) print('Original timestamp : ' + str(response.orig_time)) print('Receive timestamp : ' + str(response.recv_time)) print('Destination timestamp : ' + str(response.dest_time)) print('Reference clock identifier : ' + ntplib.ref_id_to_text(response.ref_id, response.stratum))
# # La lista de algunos servidores se hora: # https://tf.nist.gov/tf-cgi/servers.cgi # http://support.ntp.org/bin/view/Servers/StratumOneTimeServers # import datetime from time import ctime import ntplib import os try: servidor_de_tiempo = "https://tf.nist.gov/tf-cgi/servers.cgi" client = ntplib.NTPClient() response = client.request(servidor_de_tiempo, version=4) print("====================================") print("Pidiendo hora a: " + servidor_de_tiempo) print(" Offset : " + str(response.offset)) print(" Version : " + str(response.version)) print(" Date Time : " + str(ctime(response.tx_time))) print(" Leap : " + str(ntplib.leap_to_text(response.leap))) print(" Root Delay : " + str(response.root_delay)) print(" Ref Id : " + str(ntplib.ref_id_to_text(response.ref_id))) os.system("sudo date -s '" + str(ctime(response.tx_time)) + "'") print("Hora actualizada") print("====================================") except: os.system("sudo date") print("NTP Server Down Date Time NOT Set At The Startup") pass
#!/usr/bin/env python3 import ntplib import os import mod_log from time import ctime c = ntplib.NTPClient() response = c.request('it.pool.ntp.org') print (response.offset) print (response.version) print (ctime(response.tx_time)) print (ntplib.leap_to_text(response.leap)) print (response.root_delay) print (ntplib.ref_id_to_text(response.ref_id)) print(ctime(response.tx_time)) print(ntplib.system_to_ntp_time) #print (os.system) #os.system('/etc/init.d/ntpd stop, /usr/sbin/ntpdate -b -s it.pool.ntp.org, /etc/init.d/ntpd start') current_time = ctime(response.tx_time) #os.system("sudo date -s '{0}'".format(current_time)) os.system("service ntp stop") os.system(ntpdate .format(current_time) os.system("service ntp start") #self.logger.info('Raptor rozpoczal prace: {0}'.format(current_time)) #os.system('/etc/init.d/ntpd stop, /usr/sbin/ntpdate -b -s it.pool.ntp.org, /etc/init.d/ntpd start')
#!/usr/bin/env python import ntplib from time import ctime HOST_NAME = '85.199.214.98' if __name__ == '__main__': params = {} client = ntplib.NTPClient() response = client.request(HOST_NAME) print('Received time: %s' %ctime(response.tx_time)) print('ref_clock: ',ntplib.ref_id_to_text(response.ref_id, response.stratum)) print('stratum: ',response.stratum) print('last_update: ', response.ref_time) print('offset: %f' %response.offset) print('precision: ', response.precision) print('root_delay: %.6f' %response.root_delay) print('root_dispersion: %.6f' %response.root_dispersion)
#!/usr/bin/env python import ntplib from time import ctime HOST_NAME = 'pool.ntp.org' if __name__ == '__main__': params = {} client = ntplib.NTPClient() response = client.request(HOST_NAME) print('Received time: %s' % ctime(response.tx_time)) print('ref_clock: ', ntplib.ref_id_to_text(response.ref_id, response.stratum)) print('stratum: ', response.stratum) print('last_update: ', response.ref_time) print('offset: %f' % response.offset) print('precision: ', response.precision) print('root_delay: %.6f' % response.root_delay) print('root_dispersion: %.6f' % response.root_dispersion)