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 get_webservertime(host): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36' } r = requests.get(host, headers=headers) tss = r.headers['Date'] #获取http头date部分 string # print(ts) # 提取GMT时间的字符串 tsp = time.strptime(tss[5:25], "%d %b %Y %H:%M:%S") # string to time tuple ts = time.mktime(tsp) tsn = ts + 8 * 60 * 60 + 0.86 # timestamp + Beijing time + time delay , then to time tuple tsnp = time.localtime(tsn) #timestamp to local time tuple # print (tsnp) dat = "Date %u-%02u-%02u" % (tsnp.tm_year, tsnp.tm_mon, tsnp.tm_mday) tm = "Time %02u:%02u:%02u" % (tsnp.tm_hour, tsnp.tm_min, tsnp.tm_sec) print('服务器端', host, '的系统时间是', dat, tm) c = ntplib.NTPClient() #创建一个NTPClient的实例 s = c.request('ntp5.aliyun.com') #通过对象的request方法得到NTPStats的对象 current_time = s.tx_time # time stamp _date, _time = str( datetime.datetime.fromtimestamp(current_time))[:23].split(' ') # print("北京标准时间 ", str(datetime.datetime.fromtimestamp(current_time))[:23]) dif_time = round((current_time - ts - 8 * 60 * 60), 3) m, s = divmod(dif_time, 60) h, m = divmod(m, 60) # print('服务器端时间比北京标准时间慢:', dif_time,'秒') print('服务器端时间比北京标准时间慢:', int(m), '分', s, '秒') print('北京标准时间 ', _date, _time) # print(tsnp) print('本机同步前时间 ', str(datetime.datetime.now())[:23]) #.003, 毫秒级 os.system(dat) os.system(tm) print('本机同步后时间 ', str(datetime.datetime.now())[:23])
def get_time_offset(server, attempts=1): """ Returns a list of offsets for a particular server """ c = ntplib.NTPClient() res = [] for i in range(attempts): try: r = c.request(server, version=3) offset = r.offset delay = r.delay res.append(offset) except ntplib.NTPException: pass return res
def TimeSync(self, ntpServers): import ntplib c = ntplib.NTPClient() if len(ntpServers) == 0: return ntpServers = ntpServers.split(",") for ntpServer in ntpServers: try: response = c.request(ntpServer) except ntplib.NTPException, e: if ntpServer == ntpServers[-1]: msg = u"无法同步时间,请检测本地时间是否正确." LoadLog.LogMsg(self.sysLogName.warning, msg) break else: continue except:
class NTP(object): _ntp_client = ntplib.NTPClient() _last_updated = None _current_offset = 0 @classmethod def get_server_time(cls): now = datetime.now() if not cls._last_updated or ( now > (cls._last_updated + timedelta(seconds=300))): cls._last_updated = now try: cls._current_offset = cls._ntp_client.request( 'pool.ntp.org').offset except Exception as e: logging.exception(e) return datetime.now() - timedelta(milliseconds=cls._current_offset)
def autoSynchroTime(): """ 同步北京时间,执行时候,请务必用sudo,sudo,sudo 执行,否则会报权限错误,windows打开ide或者cmd请用管理员身份 :return: """ c = ntplib.NTPClient() hosts = [ 'edu.ntp.org.cn', 'tw.ntp.org.cn', 'us.ntp.org.cn', 'cn.pool.ntp.org', 'jp.ntp.org.cn' ] for host in hosts: try: response = c.request(host) if response: break except Exception as e: print(u"时区获取异常:{0}".format(e)) pass current_time = response.tx_time _date, _time = str( datetime.datetime.fromtimestamp(current_time))[:22].split(' ') print(u"正在同步时间,请耐心等待30秒左右") print(u"系统当前时间{}".format(str(datetime.datetime.now())[:22])) system = platform.system() if system == "Windows": # windows 同步时间未测试过,参考地址:https://www.jianshu.com/p/92ec15da6cc3 print(u"北京标准时间", _date, _time) a, b, c = _time.split(':') c = float(c) + 0.5 _time = "%s:%s:%s" % (a, b, c) os.system('date %s && time %s' % (_date, _time)) else: # mac同步地址,如果ntpdate未安装,brew install ntpdate linux 安装 yum install -y ntpdate os.system('ntpdate time.apple.com') print(u"同步后时间:{}".format(str(datetime.datetime.now())[:22]))
def time_ntp(server='us.pool.ntp.org'): """Similar to ``time_utc``, except uses NTP ``server`` can be any Internet or other network-based NTP server. ``time_ntp`` raises ``NTPError`` if it fails to retrieve the time from the server. """ c = ntplib.NTPClient() try: res = c.request(server, version=3) except: raise NTPError # convert from seconds since 1900 to seconds since 1970 r = res.tx_timestamp - 2208988800 # convert to utc r = time_utc(r) return r
def get_time(): hosts = [ 'edu.ntp.org.cn', 'tw.ntp.org.cn', 'us.ntp.org.cn', 'cn.pool.ntp.org', 'jp.ntp.org.cn' ] client = ntplib.NTPClient() for host in hosts: try: response = client.request(host) if response: break except Exception as e: print(host + '同步失败') pass sys_time = time.time() cur_time = response.tx_time print('相差', cur_time - sys_time) return cur_time, sys_time
def get_current_time(tz=pytz.utc, config: Optional[Dict[str, Any]] = None) -> datetime: """ Get current time from time server (NTP) and optionally apply time zone :param tz: Time zone to be applied :return: Python standard datetime """ if not config: if app: config = app.config if not config or ConfigKeys.NTPServer not in config: return tz.fromutc(datetime.utcnow()) try: c = ntplib.NTPClient() response = c.request(config[ConfigKeys.NTPServer], version=3) return datetime.fromtimestamp(response.tx_time, tz) except: return tz.fromutc(datetime.utcnow())
def set(): utc_time=time.localtime(time.time()) if (utc_time.tm_min+4)%5==0: while 1: try: c = ntplib.NTPClient() response = c.request('time.nist.gov') ts = response.tx_time print(ts) _date = time.strftime('%Y-%m-%d',time.localtime(ts)) _time = time.strftime('%X',time.localtime(ts)) os.system('date {} && time {}'.format(_date,_time)) print('%s 同步时间成功!'%time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))) break except Exception as e: print(e) pass time.sleep(60)
def __init__(self, timeserver): global OFFSET try: client = ntplib.NTPClient() response = client.request(timeserver, version=3) tn = time.time() #OFFSET = response.offset OFFSET = tn - response.tx_time + (response.offset) print(' * BTNP - ROOT Delay {:.10f}'.format(response.root_delay)) print(' * BTNP - OFFSET {:.10f}'.format(response.offset)) print(' * BTNP - TIME {:.10f}'.format(response.tx_time)) print(' * BTNP - System {:.10f}'.format(tn)) print(' * BTNP - System(af) {:.10f}'.format(tn - OFFSET)) except: print(' !- Module bntp: - Could not sync with time server.')
def initialize_time_variables(): # initializing of variables. Later, Initialization will be implemented after every five minutes global curr_time_from_GMT global start_time global GMT_log global return_time try: c = ntplib.NTPClient() # Provide the respective ntp server ip in below function response = c.request('0.asia.pool.ntp.org', version=3) response.offset curr_time_from_GMT = datetime.fromtimestamp(response.tx_time, timezone.utc); start_time = time.time() GMT_log = curr_time_from_GMT return_time = curr_time_from_GMT except Exception as e: print( "Unable to connect to GMT Server. Will rety in 60 secs.\nTime will be calculated using 'last fetched time' from GMT server.") print("------------------------------------------------------------")
def on_message(client, userdata, message): time_received = datetime.datetime.now() output_file = open("mqtt_result.csv", "a") if time.time() > time_to_sync: time_to_sync = time.time() + 1 * 60 try: client_ntp = ntplib.NTPClient() response = client_ntp.request('0.pool.ntp.org', version=3) print "prietaiso ir ntp laiko skirtumas", response.offset global offset offset = datetime.timedelta(0, response.offset) output_file.write("sync at: " + str(datetime.datetime.now() + offset) + "\n") except ntplib.NTPException: print ntplib.NTPException try: time_received += offset print "received at: ", time_received global label_mqtt label_mqtt.text = message.payload print label_mqtt.text if message.payload == "end": output_file.write(message.payload + " at: " + str(datetime.datetime.now() + offset) + "\n") output_file.close() print message.payload elif message.payload == "begin": global time_to_sync time_to_sync = time.time() + 1 * 60 output_file.write("begin at: " + str(datetime.datetime.now() + offset) + "\n") output_file.close() else: time_sent = parser.parse(message.payload) print "sent at: ", time_sent output_file.write(message.payload + "," + str(time_received) + "," + str(time_received - time_sent) + "\n") print "written" output_file.close() except: print "actions with output file failed"
def wait_for_clock_sync(ntpserver="time.nist.gov", max_wait=120): """ If this is a Raspberry Pi, wait until the system clock has been synced to to current local time. @param ntpserver: Where to get current time. @param max_wait: Length of time in seconds to wait for clock to sync. @return: """ logger.debug("Wait for clock sync called") # Manually track elapsed time to avoid using system clock elapsed = 0.0 # Run the clock sync procedure a fixed number of times before giving up for retry in range(5): try: # Get the local time from the designated NTP server client = ntplib.NTPClient() logger.debug("Calling NTPServer %s", ntpserver) response = client.request(ntpserver) t = time.time() logger.debug("Starting system clock = %f", t) logger.debug("NTPServer time = %f", response.tx_time) max_wait = float(max_wait) # Loop until system time catches up to NTP time or max wait time is exhausted while t < response.tx_time: if elapsed > max_wait: return False time.sleep(1.0) elapsed += 1.0 t = time.time() logger.debug("Current system clock = %f, delta = %f", t, response.tx_time - t) return True except Exception as ex: # During boot up, several different network errors can occur. # Basically, we keep trying until the network is up. logger.error("Exception occurred trying to sync system clock") logger.error(str(ex)) logger.debug("Waiting to retry") time.sleep(5.0) elapsed += 5.0 return False
def sync_time(self): for i in range(3): try: client = ntplib.NTPClient() response = client.request('pool.ntp.org') online_time = arrow.get(response.tx_time) local = online_time.to('Europe/Moscow') return1 = subprocess.Popen('date ' + local.format('DD-MM-YY'), shell=True).wait() return2 = subprocess.Popen('time ' + local.format('HH:mm:ss'), shell=True).wait() if return1 != 0 or return2 != 0: self.report('Not enough permissions to synchronize time.') else: self.report('Time synchronization was successful.') break except ntplib.NTPException: self.report("Time synchronization error.") time.sleep(i * i + 1)
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 print(u"windeos系统暂时不提供自动对时功能,请手动同步北京时间") # for host in hosts: # # try: # # response = c.request(host) # # if response: # break # # except Exception as e: # print(u"时区获取异常:{0}".format(e)) # current_time = response.tx_time # # _date, _time = str(datetime.datetime.fromtimestamp(current_time))[:22].split(' ') # print(u"北京标准时间", _date, _time) # # a, b, c = _time.split(':') # # c = float(c) + 0.5 # # _time = "%s:%s:%s" % (a, b, c) # # os.system('date %s && time %s' % (_date, _time)) else: # mac同步地址,如果ntpdate未安装,brew install ntpdate linux 安装 yum install -y ntpdate for host in hosts: sin = os.system('ntpdate {}'.format(host)) if sin is 0: break print(u"同步后时间:{}".format(str(datetime.datetime.now())[:22]))
def validate_time(self, ntp_server, permitted_clockskew): nas_time = datetime.datetime.now() service = self.name c = ntplib.NTPClient() try: response = c.request(ntp_server) except Exception as e: self.alert(service, f'{service}: Failed to query time from {ntp_server}. Domain may not be in connectable state.') self.logger.debug(f'[ServiceMonitorThread] Failed to query time from {ntp_server}: ({e})') return False ntp_time = datetime.datetime.fromtimestamp(response.tx_time) clockskew = abs(ntp_time - nas_time) if clockskew > permitted_clockskew: self.alert(service, f'{service}: Domain is not in connectable state. Current clockskew {clockskew} exceeds permitted clockskew of {permitted_clockskew}.') self.logger.debug(f'[ServiceMonitorThread] current clockskew of {clockskew} exceeds permitted clockskew of {permitted_clockskew}') return False else: return True
def fetch_utc_time(): ntp = ntplib.NTPClient() # Get the time. Retry up to 10 times if there is no response retries = 10 while True: try: response = ntp.request('time.nist.gov', version=3) break # Exit condition - we got the time and everything's fine except ntplib.NTPException as e: if retries == 0: # Finally give up raise e print("Exception: %s Retrying." % e) time.sleep(15) retries -= 1 return datetime.fromtimestamp(response.tx_time, timezone.utc)
def win_user(self): import win32api import ntplib conn_ntp = 1 while conn_ntp: try: conn_ntp = conn_ntp + 1 ntp_obj = ntplib.NTPClient() time_a = datetime.utcfromtimestamp( ntp_obj.request('europe.pool.ntp.org').tx_time) win32api.SetSystemTime(time_a.year, time_a.month, time_a.weekday(), time_a.day, time_a.hour, time_a.minute, time_a.second, 0) conn_ntp = 0 except: if conn_ntp == 5: conn_ntp = 0 pass
def check(self, instance): service_check_msg = None offset_threshold = instance.get('offset_threshold', DEFAULT_OFFSET_THRESHOLD) try: offset_threshold = int(offset_threshold) except (TypeError, ValueError): raise Exception( 'Must specify an integer value for offset_threshold. Configured value is %s' % repr(offset_threshold)) set_user_ntp_settings(dict(instance)) req_args = get_ntp_args() self.log.debug("Using ntp host: {0}".format(req_args['host'])) try: ntp_stats = ntplib.NTPClient().request(**req_args) except ntplib.NTPException: self.log.debug("Could not connect to NTP Server {0}".format( req_args['host'])) status = AgentCheck.UNKNOWN ntp_ts = None else: ntp_offset = ntp_stats.offset # Use the ntp server's timestamp for the time of the result in # case the agent host's clock is messed up. ntp_ts = ntp_stats.recv_time self.gauge('ntp.offset', ntp_offset, timestamp=ntp_ts) if abs(ntp_offset) > offset_threshold: status = AgentCheck.CRITICAL service_check_msg = "Offset {0} secs higher than offset threshold ({1} secs)".format( ntp_offset, offset_threshold) else: status = AgentCheck.OK self.service_check('ntp.in_sync', status, timestamp=ntp_ts, message=service_check_msg)
def __init__(self, host, port, sock=None): print("DDoS mode loaded") self.host = host self.port = port self.message = 'asdf' conn = input("How many connections do you want to make: ") ip = gethostbyname(self.host) self.num_connections = 0 # get ntp times ntpc = ntplib.NTPClient() ntp_res = ntpc.request('10.1.1.50', version=3) # connect to master self.masterHost = MS_LISTEN_HOST self.masterPort = MS_LISTEN_PORT self.sockMaster = socket(AF_INET, SOCK_STREAM) self.sockMaster.connect((self.masterHost, self.masterPort)) self.sockMaster.send('Slave offset is: {0}'.format(ntp_res.offset))
def get_ntp(local_time=0): """ Retrieves network time from a European network time server. """ if local_time: return int(time.time()) servers = [ "0.pool.ntp.org", "1.pool.ntp.org", "2.pool.ntp.org", "3.pool.ntp.org" ] for server in servers: try: client = ntplib.NTPClient() response = client.request(server) ntp = response.tx_time return ntp except Exception as e: continue return None
def __init__(self, display_interval_min): # Init the threading threading.Thread.__init__(self) # Start the display self.clock_display = display.ClockDisplay() self.clock_display.start() self.last_time_displayed = None self.display_interval_min = display_interval_min # check on the time sync. If not synched yet, then wait and break out of the loop when detected or max loop # reached ntp_client = ntplib.NTPClient() # Give some maximum time to sync, otherwise crack on. for i in range(90): try: ntp_response = ntp_client.request('europe.pool.ntp.org', version=4) # print (ntp_response.offset) if ntp_response.offset < 2: print("Synced @ {}".format(i)) break except ntplib.NTPException: print("NTP Exception ", sys.exc_info()) except socket.gaierror: print( "socket.gaierror exception - can be a problem on first boot:", sys.exc_info()) time.sleep(1) # Met Status - Start up the thread that deals with the Met Status. self.met_status_thread = met_weather_status.MetWeatherStatus() self.last_forecast = None self.forecast_interval_min = 10 self.met_status_thread.daemon = True self.met_status_thread.start()
def check(self, instance): offset_threshold = instance.get('offset_threshold', DEFAULT_OFFSET_THRESHOLD) try: offset_threshold = int(offset_threshold) except (TypeError, ValueError): raise Exception( 'Must specify an integer value for offset_threshold. Configured value is %s' % repr(offset_threshold)) set_user_ntp_settings(dict(instance)) req_args = get_ntp_args() self.log.debug("Using ntp host: {0}".format(req_args['host'])) try: ntp_stats = ntplib.NTPClient().request(**req_args) except ntplib.NTPException: self.log.debug("Could not connect to NTP Server {0}".format( req_args['host'])) ntp_offset = self.get_server_time() self.log.info("ntplib ntpexcption error:{}".format(ntp_offset)) if ntp_offset: self.update_check(ntp_offset, time.time(), offset_threshold) except socket.gaierror as e: ntp_offset = self.get_server_time() self.log.info("socker error:{}".format(ntp_offset)) if ntp_offset: self.update_check(ntp_offset, time.time(), offset_threshold) else: ntp_offset = ntp_stats.offset # Use the ntp server's timestamp for the time of the result in # case the agent host's clock is messed up. ntp_ts = ntp_stats.recv_time self.update_check(ntp_offset, ntp_ts, offset_threshold)
def main(args=None): #################### # Synchronize time # #################### try: import ntplib client = ntplib.NTPClient() response = client.request('pool.ntp.org') os.system( 'date ' + time.strftime('%m%d%H%M%Y.%S', time.localtime(response.tx_time))) except: print('Could not sync with time server.') """The main routine.""" if args is None: args = sys.argv[1:] print "version=" + version ################ # Parse config # ################ config = ConfigParser.RawConfigParser() config.file = '/etc/ble_positioning_node/config.conf' config.read(config.file) ############################### # We want reporting to kibana # ############################### LOG_CONN_POINTS = [{ 'host': config.get('Communication', 'elastic'), 'port': config.getint('Communication', 'elastic_port') }] handler = CMRESHandler(hosts=LOG_CONN_POINTS, auth_type=CMRESHandler.AuthType.NO_AUTH, use_ssl=True, es_index_name="beacon-scanner") scan = BLEScanner(handler, config) scan.main()
def check(self, instance): dimensions = self._set_dimensions(None, instance) req_args = { 'host': instance.get('host', DEFAULT_HOST), 'port': instance.get('port', DEFAULT_PORT), 'version': int(instance.get('version', DEFAULT_NTP_VERSION)), 'timeout': float(instance.get('timeout', DEFAULT_TIMEOUT)), } try: ntp_stats = ntplib.NTPClient().request(**req_args) except ntplib.NTPException: self.log.error("Could not connect to NTP Server") raise else: ntp_offset = ntp_stats.offset # Use the ntp server's timestamp for the time of the result in # case the agent host's clock is messed up. ntp_ts = ntp_stats.recv_time self.gauge('ntp.offset', ntp_offset, timestamp=ntp_ts, dimensions=dimensions)
def validate_time(ntp_server): # to do: should use UTC instead of local time. On other hand, # this is not a big con for a manual smoke-test. truenas_time = datetime.datetime.now() c = ntplib.NTPClient() try: response = c.request(ntp_server) except: return "error querying ntp_server" ntp_time = datetime.datetime.fromtimestamp(response.tx_time) # I'm only concerned about clockskew and not who is to blame. if ntp_time > truenas_time: clockskew = ntp_time - truenas_time else: clockskew = truenas_time - ntp_time return clockskew
def do_GET(self): if (self.path == '/web'): self._set_headers(200) self.wfile.write(self._text(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))) return c = ntplib.NTPClient() # Provide the respective ntp server ip in below function try: response = c.request(NTP_POOL, version=3) except ntplib.NTPException: self._set_headers(500) self.wfile.write(self._text("Timeout connecting to remote ntp server")) return if abs(response.offset) < 1: self._set_headers(200) self.wfile.write(self._text("fine " + str(response.offset))) else: self._set_headers(500) self.wfile.write(self._text("not fine " + str(response.offset)))
def getGMTtime(): global curr_time_from_GMT global start_time global GMT_log global return_time try: c = ntplib.NTPClient() # Provide the respective ntp server ip in below function response = c.request('0.asia.pool.ntp.org', version=3) response.offset curr_time_from_GMT = datetime.fromtimestamp(response.tx_time, timezone.utc); start_time = time.time() GMT_log = curr_time_from_GMT return_time = curr_time_from_GMT return return_time except Exception as e: print("unable to connect to GMT Server online. (Server Down or Connection Issue!)") print("Calculating GMT time from last fetched time from GMT Server at {} ".format(GMT_log)) return_time = curr_time_from_GMT + timedelta(seconds=time.time() - start_time) return return_time
def check(self, instance): service_check_msg = None offset_threshold = instance.get('offset_threshold', DEFAULT_OFFSET_THRESHOLD) try: offset_threshold = int(offset_threshold) except (TypeError, ValueError): raise Exception( 'Must specify an integer value for offset_threshold. Configured value is %s' % repr(offset_threshold)) req_args = { 'host': instance.get('host', DEFAULT_HOST), 'port': instance.get('port', DEFAULT_PORT), 'version': int(instance.get('version', DEFAULT_NTP_VERSION)), 'timeout': float(instance.get('timeout', DEFAULT_TIMEOUT)), } try: ntp_stats = ntplib.NTPClient().request(**req_args) except ntplib.NTPException: self.log.warning("Could not connect to NTP Server") status = AgentCheck.UNKNOWN ntp_ts = None else: ntp_offset = ntp_stats.offset # Use the ntp server's timestamp for the time of the result in # case the agent host's clock is messed up. ntp_ts = ntp_stats.recv_time self.gauge('ntp.offset', ntp_offset, timestamp=ntp_ts) if abs(ntp_offset) > offset_threshold: status = AgentCheck.CRITICAL service_check_msg = "Offset {0} secs higher than offset threshold ({1} secs)".format( ntp_offset, offset_threshold) else: status = AgentCheck.OK self.service_check('ntp.in_sync', status, timestamp=ntp_ts, message=service_check_msg)