This article introduces the Python script to set the system time method, a total of two kinds,
one is to call the socket to send UDP packets directly to the National Service Center, and the second is to call the Ntplib package。 I ping the local computer National Time Service Center address cn.pool.ntp.org sometimes dropped packets, however, both do not check whether UDP packet loss mechanism, method one after the UDP packet has been blocking state can not exit, method Two although will prompt time out, but no longer do other attempts, such as a re-contract, or to the same domain name of different IP address of the contract. As a result, an attempt was made to add a timeout mechanism to the code based on method one, and attempt to contract a different IP address for the same domain name.
The complete code for the specific changes is as follows:
#-*-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 ' + $ * ' #TimeServer_ip =socket.gethostbyname (' cn.pool.ntp.org ') #Tim eserver_ip= ' 202.118.1.130 ' port=123 for address in Timeserveraddresses:success=false count=0 and not success and Count<3:print Address,count try:client.sendto (data, (address, Port)) data, address = CLI Ent.recvfrom (1024x768) success=true except Socket.timeout:print ' Request timed out! ' Count=count+1 if success==true:a break data_result = Struct.unpack ('!12i ', data) [ten] Data_result-= time_1970 R Eturn data_resultdef SetSystemTime (now_time): Tm_year, Tm_mon, Tm_mday, Tm_hour, Tm_min, Tm_sec, Tm_wday, Tm_yday, TM_ISD st = 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 ') [1] . split (' \ n ') [1][12:].split (', ') return addresses #for address in addresses: # Res=os.popen (' Ping-n 2 ' +address) # R Esult=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) setsyste MTime (now_time) print "%d-%d-%d%d:%d:%d"% time.localtime (now_time) [: 6]
The above is the whole content of this article, I hope that everyone's study has helped.