#!/bin/bash
# change_ubuntu24.04_server_source.sh - Ubuntu 24.04 更换国内源完整脚本
set -e # 遇到错误立即退出
echo "🔄 开始更换 Ubuntu 24.04 软件源为国内镜像..."
# 检测系统版本
if ! grep -q "24.04" /etc/os-release; then
echo "❌ 此脚本仅适用于 Ubuntu 24.04"
exit 1
fi
# 备份原文件
echo "📁 备份原始源文件..."
sudo cp /etc/apt/sources.list.d/ubuntu.sources /etc/apt/sources.list.d/ubuntu.sources.backup.$(date +%Y%m%d_%H%M%S)
echo "✅ 备份完成: /etc/apt/sources.list.d/ubuntu.sources.backup"
# 创建新的阿里云源配置
echo "🔄 创建阿里云镜像源配置..."
sudo tee /etc/apt/sources.list.d/ubuntu.sources >/dev/null <<'EOF'
# 默认软件源
Types: deb
URIs: https://mirrors.aliyun.com/ubuntu
Suites: noble noble-updates noble-backports
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
# 安全更新源
Types: deb
URIs: https://mirrors.aliyun.com/ubuntu
Suites: noble-security
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
EOF
echo "✅ 源文件配置完成"
# 可选添加清华源
read -rp "是否也添加清华大学镜像源作为备选?(y/N): " add_tsinghua
if [[ $add_tsinghua =~ ^[Yy]$ ]]; then
echo "🔄 添加清华大学镜像源..."
sudo tee /etc/apt/sources.list.d/tsinghua.sources >/dev/null <<'EOF'
# 清华大学镜像源 - 主要
Types: deb
URIs: https://mirrors.tuna.tsinghua.edu.cn/ubuntu
Suites: noble noble-updates noble-backports
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
# 清华大学镜像源 - 安全更新
Types: deb
URIs: https://mirrors.tuna.tsinghua.edu.cn/ubuntu
Suites: noble-security
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
EOF
echo "✅ 清华大学镜像源添加完成"
fi
# 更新软件包列表
echo "🔄 更新软件包列表..."
sudo apt update
# 显示更新结果
echo ""
echo "==========================================="
echo "✅ 软件源更换完成!"
echo "==========================================="
echo "当前使用的镜像源:"
grep "URIs:" /etc/apt/sources.list.d/ubuntu.sources
echo ""
echo "可以运行以下命令测试速度:"
echo "sudo apt update"
echo "sudo apt upgrade -y"
echo ""
echo "如果遇到问题,可以恢复备份:"
echo "sudo cp /etc/apt/sources.list.d/ubuntu.sources.backup /etc/apt/sources.list.d/ubuntu.sources"
echo "sudo apt update"
echo "==========================================="
# 测试下载速度(可选)
read -rp "是否测试下载速度?(Y/n): " test_speed
if [[ ! $test_speed =~ ^[Nn]$ ]]; then
echo "🧪 测试下载速度..."
time sudo apt install -y --download-only htop
echo "✅ 速度测试完成"
fi