12306/config/AutoSynchroTime.py

39 lines
1.5 KiB
Python
Raw Normal View History

# coding=utf-8
import os
import platform
import ntplib
import datetime
def autoSynchroTime():
"""
同步北京时间执行时候请务必用sudosudosudo 执行否则会报权限错误windows打开ide或者cmd请用管理员身份
:return:
"""
c = ntplib.NTPClient()
2019-01-03 02:41:57 +00:00
hosts = ['ntp1.aliyun.com', 'ntp2.aliyun.com', 'ntp3.aliyun.com', 'ntp4.aliyun.com', 'cn.pool.ntp.org']
2019-01-12 07:26:02 +00:00
print(u"正在同步时间请耐心等待30秒左右如果下面有错误发送可以忽略")
2019-01-03 02:41:57 +00:00
print(u"系统当前时间{}".format(str(datetime.datetime.now())[:22]))
system = platform.system()
if system == "Windows": # windows 同步时间未测试过参考地址https://www.jianshu.com/p/92ec15da6cc3
2019-01-03 03:23:53 +00:00
for host in hosts:
2019-01-12 07:26:02 +00:00
os.popen('w32tm /register')
os.popen('net start w32time')
os.popen('w32tm /config /manualpeerlist:"{}" /syncfromflags:manual /reliable:yes /update'.format(host))
os.popen('ping -n 3 127.0.0.1 >nul')
sin = os.popen('w32tm /resync')
2019-01-03 03:23:53 +00:00
if sin is 0:
break
else: # mac同步地址如果ntpdate未安装brew install ntpdate linux 安装 yum install -y ntpdate
2019-01-03 02:41:57 +00:00
for host in hosts:
2019-01-12 07:26:02 +00:00
sin = os.popen('ntpdate {}'.format(host))
2019-01-03 02:41:57 +00:00
if sin is 0:
break
print(u"同步后时间:{}".format(str(datetime.datetime.now())[:22]))
if __name__ == '__main__':
autoSynchroTime()