From 539c304616bca93f95cac673ae431848093d7204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9D=A6?= Date: Sun, 11 May 2025 13:21:56 +0800 Subject: [PATCH] =?UTF-8?q?refactor(init):=20=E9=87=8D=E6=9E=84=20Linux=20?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除冗余的系统信息检测逻辑 - 优化 DNS 配置和时区设置 - 改进软件源配置,支持更多发行版 - 简化主执行逻辑,提高可读性 --- init/linux.sh | 131 ++++++++++++++++++++------------------------------ 1 file changed, 52 insertions(+), 79 deletions(-) diff --git a/init/linux.sh b/init/linux.sh index 69c87ce..f7bac6c 100644 --- a/init/linux.sh +++ b/init/linux.sh @@ -1,117 +1,90 @@ #!/bin/bash - set -euo pipefail echo "=== 通用 Linux 初始化脚本 ===" -# 确保为 root -if [ "$EUID" -ne 0 ]; then - echo "请以 root 用户运行此脚本。" >&2 - exit 1 -fi +# 获取系统信息 +DISTRO_ID=$(grep ^ID= /etc/os-release | cut -d= -f2 | tr -d '"') +DISTRO_NAME=$(grep ^PRETTY_NAME= /etc/os-release | cut -d= -f2 | tr -d '"') +CODENAME=$(lsb_release -cs 2>/dev/null || echo "") -# 检测系统信息 -get_os_info() { - if [ -f /etc/os-release ]; then - . /etc/os-release - DISTRO_ID=$ID - DISTRO_NAME=$NAME - DISTRO_VERSION=$VERSION_ID - else - echo "无法识别系统类型。" >&2 - exit 1 - fi -} +echo "检测到系统: $DISTRO_NAME" # 设置 DNS set_dns() { - echo "设置 DNS..." - rm -f /etc/resolv.conf - cat > /etc/resolv.conf </dev/null; then - chattr +i /etc/resolv.conf || echo "警告: 无法锁定 resolv.conf" + echo "配置 DNS 到 114.114.114.114 和 223.5.5.5..." + echo -e "nameserver 114.114.114.114\nnameserver 223.5.5.5" > /etc/resolv.conf || true +} + +# 设置时区和同步时间 +set_timezone() { + echo "设置时区为 Asia/Shanghai..." + ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime || true + if command -v timedatectl >/dev/null 2>&1; then + timedatectl set-timezone Asia/Shanghai || true + timedatectl set-ntp true || true + else + echo "timedatectl 不可用,尝试使用 ntpdate..." + (apt install -y ntpdate || yum install -y ntpdate || dnf install -y ntpdate) >/dev/null 2>&1 || true + ntpdate ntp.aliyun.com || true fi } -# 设置时区和时间同步 -set_timezone_and_time() { - echo "设置时区为 Asia/Shanghai..." - timedatectl set-timezone Asia/Shanghai 2>/dev/null || ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime - - echo "安装 ntpdate..." - $INSTALL_CMD ntpdate -y - echo "正在同步时间..." - ntpdate ntp.aliyun.com || echo "时间同步失败,请检查网络连接" -} - -# 设置清华源 +# 设置软件源 set_mirrors() { echo "更换软件源为清华镜像..." case "$DISTRO_ID" in - debian|ubuntu|raspbian) - CODENAME=$(lsb_release -cs 2>/dev/null || echo "stable") + ubuntu) + cat > /etc/apt/sources.list < /etc/apt/sources.list </dev/null; then - INSTALL_CMD="apt install -y" - apt update -y -elif command -v dnf &>/dev/null; then - INSTALL_CMD="dnf install -y" - dnf makecache -elif command -v yum &>/dev/null; then - INSTALL_CMD="yum install -y" - yum makecache -else - echo "不支持的包管理器。" >&2 - exit 1 -fi - -# 安装通用工具 -$INSTALL_CMD curl wget lsb-release || true - -# 执行配置步骤 -set_mirrors -set_dns -set_timezone_and_time - -echo "=== 初始化完成!系统已优化 ===" +main