| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- #!/bin/bash
- set -e
- REBOOT_FLAG="$1" # true / false
- ACTION="$2" # set_ntp / set_manual
- MANUAL_TIME="$3" # 手动时间(可选)
- CONFIG_FILE="/etc/speaker.conf"
- # ===== 读取配置 =====
- get_config() {
- local key="$1"
- grep "^$key=" "$CONFIG_FILE" | cut -d'=' -f2-
- }
- NTP_SERVER=$(get_config "ntpserver")
- TIMEZONE=$(get_config "tzname")
- ENABLE_NTP=$(get_config "enable_ntp")
- # 默认值兜底
- [ -z "$TIMEZONE" ] && TIMEZONE="Asia/Shanghai"
- [ -z "$NTP_SERVER" ] && NTP_SERVER="pool.ntp.org"
- echo "======================================"
- echo " Apply Time Config"
- echo "======================================"
- echo "CONFIG:"
- echo " NTP_SERVER=$NTP_SERVER"
- echo " TIMEZONE=$TIMEZONE"
- echo " ENABLE_NTP=$ENABLE_NTP"
- echo " ACTION=$ACTION"
- echo " REBOOT_FLAG=$REBOOT_FLAG"
- echo ""
- # ===== 设置时区 =====
- echo "===> 设置时区: $TIMEZONE"
- timedatectl set-timezone "$TIMEZONE"
- # ===== NTP 模式 =====
- if [ "$ACTION" = "set_ntp" ]; then
- echo "===> 模式: NTP 自动同步"
- echo "===> 写入 NTP 配置"
- cat > /etc/systemd/timesyncd.conf <<EOF
- [Time]
- NTP=$NTP_SERVER
- FallbackNTP=ntp.ubuntu.com
- EOF
- echo "===> 启用 NTP"
- timedatectl set-ntp true
- echo "===> 启用并重启 timesyncd"
- systemctl enable systemd-timesyncd
- systemctl restart systemd-timesyncd
- echo "===> 等待同步..."
- sleep 2
- # ===== 手动模式 =====
- elif [ "$ACTION" = "set_manual" ]; then
- echo "===> 模式: 手动时间"
- if [ -z "$MANUAL_TIME" ]; then
- echo "❌ 错误: 未提供手动时间"
- exit 1
- fi
- echo "===> 关闭 NTP"
- timedatectl set-ntp false
- echo "===> 停止并禁用 timesyncd"
- systemctl stop systemd-timesyncd || true
- systemctl disable systemd-timesyncd || true
- echo "===> 设置时间: $MANUAL_TIME"
- timedatectl set-time "$MANUAL_TIME"
- echo "===> 写入 RTC(防止重启丢失)"
- hwclock --systohc
- else
- echo "❌ 未知操作: $ACTION"
- exit 1
- fi
- # ===== 状态输出 =====
- echo ""
- echo "======================================"
- echo " 当前状态"
- echo "======================================"
- timedatectl status
- echo ""
- echo "===> timesync 信息"
- timedatectl show-timesync --all | grep -E 'ServerName|NTP|Fallback' || true
- echo ""
- echo "===> timesyncd 服务状态"
- systemctl is-enabled systemd-timesyncd || true
- systemctl is-active systemd-timesyncd || true
- # ===== 是否重启 =====
- if [ "$REBOOT_FLAG" = "true" ]; then
- echo ""
- echo "===> 系统即将重启..."
- sleep 2
- reboot
- fi
- echo "======================================"
- echo " 完成"
- echo "======================================"
- exit 0
|