吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 163|回复: 2
收起左侧

[学习记录] Python同步linux时间

[复制链接]
kk3201 发表于 2025-3-14 14:16
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# !/usr/bin/env python3
"""
Linux时间同步脚本
此脚本通过NTP协议从指定的时间服务器获取当前时间并更新系统时钟
需要root权限执行
"""
 
import subprocess
import logging
import argparse
import os
from datetime import datetime
 
# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='./time_sync.log',
    filemode='a'
)
 
 
def check_root_privileges():
    """检查脚本是否以root权限运行"""
    if os.geteuid() != 0:
        logging.error("此脚本需要root权限运行")
        print("错误: 此脚本需要root权限运行")
        exit(1)
 
 
def sync_time(server, timeout=5):
    """
    从指定的NTP服务器同步时间
 
    参数:
        server (str): NTP服务器地址
        timeout (int): 连接超时时间(秒)
 
    返回:
        dict: 包含同步状态和详细信息的字典
    """
    try:
        # 使用ntpdate命令同步时间
        logging.info(f"正在尝试从 {server} 同步时间...")
        result = subprocess.run(
            ["ntpdate", "-u", "-t", str(timeout), server],
            capture_output=True,
            text=True,
            check=True
        )
 
        output = result.stdout.strip()
        logging.info(f"时间同步成功: {output}")
 
        # 返回包含状态和详细信息的字典
        return {
            "success": True,
            "message": output,
            "time_adjustment": parse_time_adjustment(output)
        }
 
    except subprocess.CalledProcessError as e:
        error_msg = e.stderr.strip()
        logging.error(f"同步时间失败: {error_msg}")
        return {
            "success": False,
            "message": error_msg,
            "time_adjustment": None
        }
    except Exception as e:
        error_msg = str(e)
        logging.error(f"发生未知错误: {error_msg}")
        return {
            "success": False,
            "message": error_msg,
            "time_adjustment": None
        }
 
 
def parse_time_adjustment(output):
    """
    解析ntpdate输出,提取时间调整信息
 
    参数:
        output (str): ntpdate命令的输出
 
    返回:
        float: 时间调整值(秒),如果无法解析则返回None
    """
    try:
        # ntpdate输出格式通常包含"offset X.XXXXX seconds"
        import re
        match = re.search(r'offset (-?\d+\.\d+) seconds', output)
        if match:
            return float(match.group(1))
        return None
    except Exception:
        return None
 
 
def update_hardware_clock():
    """
    将系统时间同步到硬件时钟
 
    返回:
        dict: 包含操作状态和详细信息的字典
    """
    try:
        logging.info("正在更新硬件时钟...")
        result = subprocess.run(
            ["hwclock", "--systohc"],
            capture_output=True,
            text=True,
            check=True
        )
 
        output = result.stdout.strip()
        logging.info("硬件时钟更新成功")
 
        return {
            "success": True,
            "message": output if output else "硬件时钟已成功更新"
        }
    except subprocess.CalledProcessError as e:
        error_msg = e.stderr.strip()
        logging.error(f"更新硬件时钟失败: {error_msg}")
        return {
            "success": False,
            "message": error_msg
        }
    except Exception as e:
        error_msg = str(e)
        logging.error(f"更新硬件时钟时发生未知错误: {error_msg}")
        return {
            "success": False,
            "message": error_msg
        }
 
 
def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="Linux系统时间同步脚本")
    parser.add_argument("-s", "--server", default="ntp.aliyun.com",
                        help="指定NTP服务器 (默认: ntp.aliyun.com)")
    parser.add_argument("-t", "--timeout", type=int, default=5,
                        help="连接超时时间(秒)(默认: 5)")
    parser.add_argument("--no-hwclock", action="store_true",
                        help="不更新硬件时钟")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="显示详细输出信息")
 
    args = parser.parse_args()
 
    # 检查root权限
    check_root_privileges()
 
    # 记录开始执行时间
    start_time = datetime.now()
    logging.info(f"时间同步开始于 {start_time}")
    print(f"开始同步时间,服务器: {args.server}")
 
    # 同步时间
    sync_result = sync_time(args.server, args.timeout)
 
    if sync_result["success"]:
        print("系统时间同步成功")
        if args.verbose and sync_result["time_adjustment"] is not None:
            print(f"时间调整: {sync_result['time_adjustment']} 秒")
 
        # 更新硬件时钟
        if not args.no_hwclock:
            hw_result = update_hardware_clock()
            if hw_result["success"]:
                print("硬件时钟更新成功")
            else:
                print(f"硬件时钟更新失败: {hw_result['message']}")
    else:
        print(f"时间同步失败: {sync_result['message']}")
 
    # 记录结束时间
    end_time = datetime.now()
    logging.info(f"时间同步结束于 {end_time}")
    logging.info(f"执行总时间: {end_time - start_time}")
 
 
if __name__ == "__main__":
    main()

运行截图

运行截图

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

小酒窝 发表于 2025-3-14 15:03
怎么执行和编译?
 楼主| kk3201 发表于 2025-3-18 08:01
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-3-30 21:21

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表