#!/usr/bin/env python # coding: utf8 # Usage: 指定ntpserver域名到ntpserver_domains变量即可 import socket import struct import time import win32api import subprocess import os import sys def gettime(ntpserver_ips): TIME_1970 = 2208988800L client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.settimeout(3) data = '\x1b' + 47 * '\0' Port=123 for server in ntpserver_ips: success = False count = 1 '''每个ip尝试3次''' while not success and count < 4: try: client.sendto(data, (server, Port)) data = client.recvfrom(1024)[0] success = True print server+' get time success, tried '+str(count)+' times.' except socket.timeout: print server+' get time failed, tried '+str(count)+' times.' count += 1 if success == True: break data_result = struct.unpack('!12I', data)[10] data_result -= TIME_1970 return data_result def settime(nowtime): tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(nowtime) win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0) print u'Set system time success.' def getip_with_domains(ntpserver_domains): ips = [] for i in ntpserver_domains: ip = socket.gethostbyname_ex(i)[2] ips.extend(ip) return ips if __name__ == '__main__': ntpserver_domains = ['cn.pool.ntp.org', 'ntp.sjtu.edu.cn', 'time.windows.com'] ntpserver_ips = getip_with_domains(ntpserver_domains) if not ntpserver_ips or len(ntpserver_ips) != len(set(ntpserver_ips)): print u'Some domain can not resolve ip.' print os.system('pause') sys.exit() else: nowtime = gettime(ntpserver_ips) settime(nowtime) print u'Now Time:',time.strftime('%Y-%m-%d %X') os.system('pause')
python windows系统时间同步
原创
©著作权归作者所有:来自51CTO博客作者0x7F的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:win7下ramdisk优化
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
windows使用csRsync同步文件到linuxrsync cwrsync 编码 同步 密码
-
设置windows 时间同步间隔
win+r】快捷键打开【运行】窗口,根据下图所示,在方框中输
html 时间间隔 ide