python指令碼設定逾時機制系統時間的方法

來源:互聯網
上載者:User
本文為大家介紹了python指令碼設定系統時間的方法,一共有兩種, 其一是調用socket直接發送udp包到國家授時中心,其二是調用ntplib包。我在本地電腦ping 國家授時中心地址cn.pool.ntp.org有時出現丟包,然而,二者都沒有檢查udp是否丟包的機制,方法一在udp丟包後一直處於阻塞狀態無法退出,方法二雖然會提示逾時,但是不再做其它嘗試,比如重新發包,或者向同一個網域名稱的不同IP地址發包。於是,嘗試在方法一的代碼基礎上,增加了逾時機制,並且嘗試向同一個網域名稱的不同IP地址發包。

具體修改後的完整代碼如下:

#-*- coding:utf-8 -*-import socketimport structimport timeimport win32apiimport osimport redef getTime(TimeServerAddresses):  TIME_1970 = 2208988800L  client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  client.settimeout(3)  data = '\x1b' + 47 * '\0'  #TimeServer_ip=socket.gethostbyname('cn.pool.ntp.org')  #TimeServer_ip='202.118.1.130'  Port=123  for address in TimeServerAddresses:    success=False    count=0    while not success and count<3:      print address,count      try:        client.sendto(data, (address, Port))        data, address = client.recvfrom(1024)        success=True      except socket.timeout:        print 'Request timed out!'        count=count+1    if success==True:a      break  data_result = struct.unpack('!12I', data)[10]  data_result -= TIME_1970  return data_resultdef setSystemTime(now_time):  tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(now_time)  win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0)  print "Set System OK!"def getServerIP():  res1=os.popen('nslookup cn.pool.ntp.org')  result1=res1.read()  addresses=result1.split('\n\n')[1].split('\n')[1][12:].split(',')  return addresses  #for address in addresses:  #  res=os.popen('ping -n 2 '+address)  #  result=res.read()  #  received_num=int(re.findall('Received = [0-9]',result)[0].split('=')[1])  #  if received_num > 1:  #    break  #TimeServer=addressif __name__ == '__main__':  addresses=getServerIP()  now_time=getTime(addresses)  setSystemTime(now_time)  print "%d-%d-%d %d:%d:%d" % time.localtime(now_time)[:6]

以上就是本文的全部內容,希望對大家的學習有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.