如何用脚本校准时间

wen 实用脚本 2

本文目录导读:

如何用脚本校准时间

  1. Linux/Unix 系统
  2. PowerShell 脚本(Windows)
  3. Python 脚本(跨平台)
  4. 批量同步脚本(适用于多台服务器)
  5. 定时自动同步脚本
  6. 使用 Docker 容器
  7. 使用建议

Linux/Unix 系统

Windows 时间同步脚本(适用于Linux)

#!/bin/bash
# 使用 NTP 服务器同步时间
# 安装 NTP 工具(如果需要)
sudo apt-get install ntpdate  # Debian/Ubuntu
# sudo yum install ntpdate    # CentOS/RHEL
# 同步时间
sudo ntpdate -u pool.ntp.org
# 或者使用 systemd-timesyncd
sudo timedatectl set-ntp true

使用 chrony(更现代的替代方案)

#!/bin/bash
# 安装 chrony
sudo apt-get install chrony  # Debian/Ubuntu
# 启动并启用服务
sudo systemctl start chronyd
sudo systemctl enable chronyd
# 立即同步
sudo chronyc makestep

PowerShell 脚本(Windows)

# Windows 时间同步脚本
# 以管理员身份运行
# 同步到 Microsoft 时间服务器
w32tm /resync /force
# 或者指定其他 NTP 服务器
w32tm /config /manualpeerlist:"pool.ntp.org" /syncfromflags:manual /reliable:YES /update
w32tm /resync
# 设置自动时间同步
Set-Service -Name w32time -StartupType 'Automatic'
Start-Service w32time

Python 脚本(跨平台)

#!/usr/bin/env python3
import subprocess
import sys
import socket
import ntplib
from datetime import datetime
import os
def sync_time_ntp():
    """使用 NTP 协议同步时间"""
    try:
        # 使用 ntplib 获取 NTP 服务器时间
        client = ntplib.NTPClient()
        response = client.request('pool.ntp.org', version=3)
        # 获取 NTP 服务器时间
        ntp_time = datetime.fromtimestamp(response.tx_time)
        print(f"NTP 服务器时间: {ntp_time}")
        # 根据操作系统执行时间设置
        if sys.platform == 'win32':
            # Windows 使用 PowerShell 命令
            cmd = f'powershell "Set-Date \'{ntp_time.strftime("%Y-%m-%d %H:%M:%S")}\'"'
        elif sys.platform == 'linux' or sys.platform == 'darwin':
            # Linux/Mac 使用 date 命令
            cmd = f'date -s "{ntp_time.strftime("%Y-%m-%d %H:%M:%S")}"'
        else:
            print("不支持的操作系统")
            return False
        # 执行命令
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            print("时间同步成功!")
            return True
        else:
            print(f"时间同步失败: {result.stderr}")
            return False
    except Exception as e:
        print(f"错误: {e}")
        return False
def sync_time_system():
    """使用系统命令同步时间"""
    try:
        if sys.platform == 'win32':
            # Windows 使用 w32tm
            subprocess.run(['w32tm', '/resync', '/force'], check=True, capture_output=True)
        elif sys.platform == 'linux':
            # Linux 使用 ntpdate 或 timedatectl
            try:
                subprocess.run(['sudo', 'ntpdate', '-u', 'pool.ntp.org'], check=True, capture_output=True)
            except:
                subprocess.run(['sudo', 'timedatectl', 'set-ntp', 'true'], check=True, capture_output=True)
        else:
            print("不支持的操作系统")
            return False
        print("系统时间同步成功!")
        return True
    except Exception as e:
        print(f"系统同步失败: {e}")
        return False
if __name__ == "__main__":
    print("开始同步时间...")
    # 优先通过网络获取时间
    if not sync_time_ntp():
        print("尝试使用系统同步...")
        sync_time_system()

批量同步脚本(适用于多台服务器)

#!/bin/bash
# 远程服务器时间同步脚本
# 服务器列表文件 (每行一个IP或主机名)
SERVERS_FILE="servers.txt"
# SSH 用户
SSH_USER="root"
# SSH 密钥
SSH_KEY="$HOME/.ssh/id_rsa"
# 检查服务器列表是否存在
if [ ! -f "$SERVERS_FILE" ]; then
    echo "服务器列表文件不存在: $SERVERS_FILE"
    exit 1
fi
echo "开始同步所有服务器的时间..."
while read server; do
    [ -z "$server" ] && continue  # 跳过空行
    echo "正在同步 $server ..."
    ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$SSH_USER@$server" \
        "sudo ntpdate pool.ntp.org && echo '同步成功' || echo '同步失败'"
done < "$SERVERS_FILE"
echo "所有服务器时间同步完成"

定时自动同步脚本

#!/bin/bash
# 添加到 crontab 实现定时同步
# crontab 配置(每天凌晨 2 点执行)
# 0 2 * * * /path/to/time_sync.sh
echo "=== 时间同步脚本 ==="
echo "开始时间: $(date)"
# 检查网络连接
if ! ping -c 1 pool.ntp.org > /dev/null 2>&1; then
    echo "无法连接到 NTP 服务器"
    exit 1
fi
# 执行时间同步
if command -v ntpdate &> /dev/null; then
    sudo ntpdate -u pool.ntp.org
elif command -v chronyc &> /dev/null; then
    sudo chronyc makestep
elif command -v timedatectl &> /dev/null; then
    sudo timedatectl set-ntp true
else
    echo "没有找到可用的时间同步工具"
    exit 1
fi
echo "同步完成: $(date)"

使用 Docker 容器

# docker-compose.yml
version: '3'
services:
  timesync:
    image: alpine
    network_mode: host
    volumes:
      - ./auto-time-sync.sh:/scripts/auto-time-sync.sh
    entrypoint: ["/bin/sh", "-c"]
    command: |
      apk add --no-cache chrony ntp
      while true; do
        chronyc makestep
        ntpdate pool.ntp.org
        sleep 3600
      done

使用建议

  1. 权限要求:这些脚本通常需要管理员/root 权限
  2. 网络要求:需要能访问 NTP 服务器
  3. 安全考虑:使用 HTTPS 或可信的同步源
  4. 日志记录:建议添加日志输出便于排查问题

选择哪种方法取决于你的操作系统和具体需求,对于大多数情况,直接使用系统的 NTP 服务(如 timedatectlw32time)是最简单可靠的选择。

抱歉,评论功能暂时关闭!