python根据网络时间修改本地时间

简介

由于本人电脑时间经常错误,于是编写了此代码,以方便修改时间。
如有不足之处,请指正。

code

import subprocess
import logging
from datetime import datetime
import http.client
import time

class System_Time:

    def __init__(self):
        self.__newtime = None

    @property
    def newtime(self):
        return self.__newtime

    @newtime.setter
    def newtime(self, value):
        self.__newtime = value

    def get_sys_now_time(self):
        return datetime.strftime(datetime.now(),"%H:%M:%S")

    def get_webservertime(self, host='www.baidu.com'):
        conn = http.client.HTTPConnection(host)
        conn.request("GET", "/")
        r = conn.getresponse()
        # r.getheaders() #获取所有的http头
        ts = r.getheader('date')  # 获取http头date部分
        # 将GMT时间转换成北京时间
        ltime = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
        # print(ltime)
        ttime = time.localtime(time.mktime(ltime) + 8 * 60 * 60)
        # print(ttime)
        dat = "%u-%02u-%02u" % (ttime.tm_year, ttime.tm_mon, ttime.tm_mday)
        tm = "%02u:%02u:%02u" % (ttime.tm_hour, ttime.tm_min, ttime.tm_sec)
        # print("dat:{}".format(dat))
        print("tm:{}".format(tm))
        return tm

    @classmethod
    def alter(cls):
        obj = cls()
        webtm = obj.get_webservertime()
        obj.newtime = webtm
        # print(obj.newtime)
        try:
            ps = subprocess.Popen(
                'time',
                universal_newlines=True,
                shell=True,
                stdout=subprocess.PIPE,
                stdin=subprocess.PIPE
            )

            ps.communicate(obj.newtime, 15)
            logging.basicConfig(level=logging.NOTSET)
            if ps.poll() is not None:
                logging.info("进程成功终止")
            else:
                logging.warning("进程未终止")

            if ps.returncode == 0:
                logging.info("系统时间修改成功")
            elif ps.returncode > 0:
                logging.warning("进程异常:{}".format(ps.returncode))
            elif ps.returncode < 0 or ps.returncode > 10000:
                logging.error("进程错误")
        except Exception as error:
            print(error.__str__())


if __name__ == '__main__':
    System_Time.alter()

运行结果示例:

在这里插入图片描述
)

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成离线的授权码可以使用 Python 中的加密算法,例如AES或RSA等。同时,为了添加有效期并防止本地时间修改,可以使用服务器时间来生成授权码,并将有效期信息嵌入到授权码中。具体实现步骤如下: 1.获取服务器时间 可以使用 Python 中的datetime模块来获取服务器时间,例如: ```python import datetime server_time = datetime.datetime.now() ``` 2.生成授权码 可以使用 Python 中的加密算法,例如AES或RSA等来生成授权码。这里以AES算法为例,可以使用Python中的cryptography库来生成授权码,例如: ```python from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) license_info = 'valid until 2022-01-01' license_token = cipher_suite.encrypt(license_info.encode()) ``` 这里生成了一个随机的加密密钥,并使用该密钥生成了一个加密器,然后将有效期信息加密成授权码。 3.验证授权码 在验证授权码时,可以先解密授权码,然后检查其中的有效期信息是否在当前服务器时间之前。如果有效期信息在当前时间之前,则授权码无效。例如: ```python license_info = cipher_suite.decrypt(license_token).decode() valid_until = datetime.datetime.strptime(license_info, 'valid until %Y-%m-%d') if server_time >= valid_until: print('License expired!') else: print('License valid.') ``` 这里使用相同的加密密钥解密了授权码,并将有效期信息转换为datetime对象,然后比较当前服务器时间和有效期信息即可。 4.防止本地时间修改 为了防止本地时间修改,可以使用网络时间协议(NTP)来获取准确的时间Python中有一个ntp包,可以使用该包获取网络时间。例如: ```python import ntplib ntp_client = ntplib.NTPClient() response = ntp_client.request('pool.ntp.org') ntp_time = datetime.datetime.fromtimestamp(response.tx_time) ``` 这里使用了pool.ntp.org作为NTP服务器,并获取了当前的网络时间。如果本地时间修改,那么获取到的网络时间与本地时间将不同,从而可以检测到时间修改的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值