用脚本检测并修复时间服务

wen 实用脚本 1

本文目录导读:

用脚本检测并修复时间服务

  1. 跨平台时间服务检测修复脚本
  2. 使用方法
  3. 功能说明
  4. 注意事项

我来为您提供一个检测并修复时间服务的脚本,这个脚本支持 Windows 和 Linux 系统。

跨平台时间服务检测修复脚本

Windows 版本 (repair_time.bat)

@echo off
chcp 65001 >nul时间服务检测修复工具
color 0A
echo ========================================
echo    时间服务检测与修复工具
echo    Windows 版本
echo ========================================
echo.
:menu
echo 请选择操作:
echo 1. 检测并修复时间服务
echo 2. 同步网络时间
echo 3. 更改时间服务器
echo 4. 退出
echo.
set /p choice=请输入选项 (1-4): 
if "%choice%"=="1" goto check_and_fix
if "%choice%"=="2" goto sync_time
if "%choice%"=="3" goto change_server
if "%choice%"=="4" exit /b 0
echo 无效选项,请重新输入
goto menu
:check_and_fix
echo.
echo [步骤 1] 检查时间服务状态...
sc query w32time | findstr "RUNNING"
if %errorlevel% equ 0 (
    echo [√] 时间服务正在运行
) else (
    echo [×] 时间服务未运行,正在启动...
    net start w32time
    if %errorlevel% equ 0 (
        echo [√] 时间服务启动成功
    ) else (
        echo [×] 时间服务启动失败,请以管理员身份运行此脚本
        pause
        exit /b 1
    )
)
echo.
echo [步骤 2] 检查服务配置...
w32tm /query /configuration | findstr "AnnounceFlags"
if %errorlevel% equ 0 (
    echo [√] 服务配置正常
) else (
    echo [×] 服务配置异常,尝试修复...
    w32tm /config /syncfromflags:manual /manualpeerlist:"time.windows.com"
    w32tm /config /update
    echo [√] 配置已更新
)
echo.
echo [步骤 3] 检查注册表设置...
reg query "HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient" /v Enabled >nul 2>&1
if %errorlevel% equ 0 (
    echo [√] NTP客户端已启用
) else (
    echo [×] NTP客户端未启用,正在修复...
    reg add "HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient" /v Enabled /t REG_DWORD /d 1 /f
    echo [√] NTP客户端已启用
)
echo.
echo [步骤 4] 重新注册时间服务...
regsvr32 /s w32time.dll
regsvr32 /s w32tm.dll
echo [√] 时间服务组件已重新注册
echo.
echo [步骤 5] 同步时间...
w32tm /resync
if %errorlevel% equ 0 (
    echo [√] 时间同步成功
) else (
    echo [×] 时间同步失败,请检查网络连接
)
echo.
echo 当前系统时间:%date% %time%
echo.
pause
goto menu
:sync_time
echo.
echo 正在同步网络时间...
w32tm /resync
if %errorlevel% equ 0 (
    echo [√] 时间同步成功
) else (
    echo [×] 时间同步失败
    echo 尝试强制同步...
    w32tm /resync /force
)
echo 当前系统时间:%date% %time%
echo.
pause
goto menu
:change_server
echo.
echo 当前时间服务器:time.windows.com
echo.
echo 选择时间服务器:
echo 1. time.windows.com (默认)
echo 2. time.nist.gov
echo 3. pool.ntp.org
echo 4. cn.pool.ntp.org (中国)
echo 5. 自定义
echo.
set /p server_choice=请输入选项 (1-5): 
if "%server_choice%"=="1" set server=time.windows.com
if "%server_choice%"=="2" set server=time.nist.gov
if "%server_choice%"=="3" set server=pool.ntp.org
if "%server_choice%"=="4" set server=cn.pool.ntp.org
if "%server_choice%"=="5" (
    set /p server=请输入时间服务器地址: 
)
w32tm /config /syncfromflags:manual /manualpeerlist:"%server%"
w32tm /config /update
echo [√] 时间服务器已更改为:%server%
echo.
pause
goto menu

Linux 版本 (repair_time.sh)

#!/bin/bash
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}错误:此脚本需要root权限运行${NC}"
        echo "请使用 sudo bash $0 运行"
        exit 1
    fi
}
# 检测系统类型
detect_system() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$ID
    elif [ -f /etc/redhat-release ]; then
        OS="rhel"
    elif [ -f /etc/debian_version ]; then
        OS="debian"
    else
        echo -e "${RED}无法检测系统类型${NC}"
        exit 1
    fi
    echo -e "${GREEN}检测到系统:${OS}${NC}"
}
# 检查时间同步服务状态
check_service() {
    echo -e "${YELLOW}[步骤 1] 检查时间同步服务...${NC}"
    # 检查 timesyncd 或 chrony 或 ntp
    if command -v timedatectl &> /dev/null; then
        if timedatectl status | grep -q "NTP service: active"; then
            echo -e "${GREEN}[√] systemd-timesyncd 正在运行${NC}"
            return 0
        fi
    fi
    if systemctl is-active chronyd &> /dev/null; then
        echo -e "${GREEN}[√] chronyd 正在运行${NC}"
        return 0
    fi
    if systemctl is-active ntp &> /dev/null; then
        echo -e "${GREEN}[√] ntp 正在运行${NC}"
        return 0
    fi
    if systemctl is-active ntpdate &> /dev/null; then
        echo -e "${GREEN}[√] ntpdate 正在运行${NC}"
        return 0
    fi
    echo -e "${RED}[×] 未检测到运行中的时间同步服务${NC}"
    return 1
}
# 安装时间同步服务
install_service() {
    echo -e "${YELLOW}[步骤 2] 安装时间同步服务...${NC}"
    case $OS in
        ubuntu|debian)
            apt-get update
            apt-get install -y ntp ntpdate
            systemctl enable ntp
            systemctl start ntp
            ;;
        centos|rhel|fedora)
            yum install -y chrony ntpdate
            systemctl enable chronyd
            systemctl start chronyd
            ;;
        *)
            echo -e "${RED}不支持的 Linux 发行版${NC}"
            exit 1
            ;;
    esac
    echo -e "${GREEN}[√] 时间同步服务安装完成${NC}"
}
# 配置时间服务器
configure_ntp() {
    echo -e "${YELLOW}[步骤 3] 配置时间服务器...${NC}"
    # 备用的 NTP 服务器列表
    NTP_SERVERS=(
        "pool.ntp.org"
        "cn.pool.ntp.org"
        "time.nist.gov"
        "time.windows.com"
    )
    # 配置 chrony
    if [ -f /etc/chrony.conf ]; then
        echo -e "${GREEN}配置 chrony...${NC}"
        # 备份原配置
        cp /etc/chrony.conf /etc/chrony.conf.backup
        # 写入新配置
        cat > /etc/chrony.conf << EOF
# 使用 pool 配置时间服务器
pool ${NTP_SERVERS[0]} iburst
pool ${NTP_SERVERS[1]} iburst
# 记录时钟漂移
driftfile /var/lib/chrony/drift
# 允许同步
makestep 1.0 3
# 允许客户端查询
allow 127.0.0.1
# 日志
log measurements statistics tracking
EOF
        systemctl restart chronyd
        echo -e "${GREEN}[√] chrony 配置完成${NC}"
    fi
    # 配置 ntp
    if [ -f /etc/ntp.conf ]; then
        echo -e "${GREEN}配置 NTP...${NC}"
        cp /etc/ntp.conf /etc/ntp.conf.backup
        cat > /etc/ntp.conf << EOF
# 服务器配置
server ${NTP_SERVERS[0]} iburst
server ${NTP_SERVERS[1]} iburst
server ${NTP_SERVERS[2]} iburst
# 限制访问
restrict 127.0.0.1
restrict ::1
# 记录
driftfile /var/lib/ntp/ntp.drift
EOF
        systemctl restart ntp
        echo -e "${GREEN}[√] NTP 配置完成${NC}"
    fi
}
# 同步时间
sync_time() {
    echo -e "${YELLOW}[步骤 4] 同步时间...${NC}"
    # 尝试多种方式同步
    if command -v ntpdate &> /dev/null; then
        echo -e "${GREEN}使用 ntpdate 同步...${NC}"
        ntpdate -u pool.ntp.org 2>/dev/null || ntpdate -u cn.pool.ntp.org
    elif command -v chronyc &> /dev/null; then
        echo -e "${GREEN}使用 chronyc 同步...${NC}"
        chronyc -a makestep 2>/dev/null
    elif command -v timedatectl &> /dev/null; then
        echo -e "${GREEN}使用 timedatectl 同步...${NC}"
        timedatectl set-ntp true
        sleep 2
    fi
    echo -e "${GREEN}[√] 时间同步完成${NC}"
}
# 检查系统时间准确性
check_time_accuracy() {
    echo -e "${YELLOW}[步骤 5] 检查时间准确性...${NC}"
    current_time=$(date +%s)
    # 通过多个来源获取时间
    if command -v ntpdate &> /dev/null; then
        ntp_time=$(ntpdate -q pool.ntp.org 2>/dev/null | head -1 | awk '{print $1, $2}')
        if [ ! -z "$ntp_time" ]; then
            echo -e "${GREEN}当前系统时间: $(date)${NC}"
            echo -e "${GREEN}网络时间: ${ntp_time}${NC}"
            # 检查时间差
            current_epoch=$(date +%s)
            ntp_epoch=$(date -d "$ntp_time" +%s 2>/dev/null)
            if [ ! -z "$ntp_epoch" ]; then
                time_diff=$((current_epoch - ntp_epoch))
                abs_diff=${time_diff#-}
                if [ $abs_diff -gt 60 ]; then
                    echo -e "${YELLOW}[!] 时间偏差超过1分钟,建议重新同步${NC}"
                else
                    echo -e "${GREEN}[√] 时间偏差在可接受范围内${NC}"
                fi
            fi
        fi
    fi
}
# 显示硬件时钟状态
check_hardware_clock() {
    echo -e "${YELLOW}[步骤 6] 检查硬件时钟...${NC}"
    if [ -f /sys/class/rtc/rtc0/time ]; then
        hw_time=$(cat /sys/class/rtc/rtc0/time)
        sys_time=$(date +%H:%M:%S)
        echo -e "${GREEN}硬件时钟: ${hw_time}${NC}"
        echo -e "${GREEN}系统时钟: ${sys_time}${NC}"
        # 同步硬件时钟
        if command -v hwclock &> /dev/null; then
            hwclock --systohc
            echo -e "${GREEN}[√] 硬件时钟已同步${NC}"
        fi
    fi
}
# 主菜单
main_menu() {
    clear
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}   时间服务检测与修复工具${NC}"
    echo -e "${GREEN}   Linux 版本${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo "1. 自动检测并修复"
    echo "2. 仅检查状态"
    echo "3. 仅同步时间"
    echo "4. 配置时间服务器"
    echo "5. 退出"
    echo ""
}
# 主程序
main() {
    check_root
    detect_system
    while true; do
        main_menu
        read -p "请输入选项 (1-5): " choice
        case $choice in
            1)
                check_service
                if [ $? -ne 0 ]; then
                    install_service
                fi
                configure_ntp
                sync_time
                check_time_accuracy
                check_hardware_clock
                echo -e "${GREEN}[√] 时间服务修复完成${NC}"
                ;;
            2)
                check_service
                check_time_accuracy
                ;;
            3)
                sync_time
                ;;
            4)
                configure_ntp
                ;;
            5)
                echo -e "${GREEN}感谢使用!${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}无效选项,请重新选择${NC}"
                ;;
        esac
        echo ""
        read -p "按 Enter 键继续..."
    done
}
# 运行主程序
main

使用方法

Windows 系统:

  1. 以管理员身份运行命令提示符
  2. 执行 repair_time.bat
  3. 选择对应的选项进行操作

Linux 系统:

# 赋予执行权限
chmod +x repair_time.sh
# 以root权限运行
sudo ./repair_time.sh

功能说明

Windows 版本包含:

  • 检查时间服务状态
  • 修复服务配置
  • 检查注册表设置
  • 重新注册组件
  • 同步网络时间
  • 更改时间服务器

Linux 版本包含:

  • 检测系统类型
  • 检查时间同步服务
  • 安装缺失的服务
  • 配置NTP服务器
  • 同步时间
  • 检查时间准确性
  • 同步硬件时钟

注意事项

  1. 权限要求:Windows需要管理员权限,Linux需要root权限
  2. 网络连接:确保网络连通以获取时间服务器
  3. 防火墙设置:可能需要开放 UDP 123 端口(NTP协议使用)
  4. 资产兼容性:某些企业环境可能有自定义的时间服务器配置

这个脚本提供了完整的时间服务检测、修复和配置功能,适用于大多数常见问题场景。

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