环境:Ubuntu 22.04 LTS(VMware) 目标:将默认国外源切换为清华镜像,提升依赖下载速度并避免连接错误 预计耗时:约 5 分钟
整体流程
备份 → 替换镜像源 → 更新软件列表 → 升级软件
1. 安全备份原有软件源
为防止换源失败后无法还原,需先备份原配置文件。
操作步骤:
cd /etc/apt
sudo cp sources.list sources.list.bak
验证备份:
ls sources.list*
若回显中包含 sources.list 和 sources.list.bak,说明备份成功。若后续换源失败,可通过 sudo cp sources.list.bak sources.list 快速恢复。
2. 替换官方源为清华源
使用 sed 命令批量替换 sources.list 中的域名。
操作步骤:
# 替换 archive.ubuntu.com
sudo sed -i 's|http://.*.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' sources.list
# 替换 security.ubuntu.com
sudo sed -i 's|http://security.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' sources.list
命令说明:
sudo:以超级用户权限运行,确保有写权限。sed -i:原地编辑文件,不生成临时副本。s|...|...|g:全局替换匹配到的 URL。sources.list:待修改的配置文件路径。
验证替换:
grep tuna sources.list
若输出包含 https://mirrors.tuna.tsinghua.edu.cn,说明替换成功。
3. 更新软件列表
同步本地软件包索引。
操作步骤:
sudo apt update
终端显示 Reading package lists... Done 表示成功。若出现 404 或连接错误,说明换源未生效。
4. 升级已装软件
根据最新列表升级现有软件。
操作步骤:
apt upgrade -y

