跳到主要内容

操作

2024年07月31日
柏拉文
越努力,越幸运

一、切换镜像源


1. 创建名为 switch_yum_repo.sh 脚本

#!/bin/bash

set -e # 遇到错误时停止脚本执行

# 定义变量
NEW_REPO_URL="https://mirrors.aliyun.com/repo"
REPO_DIR="/etc/yum.repos.d"
BACKUP_REPO_DIR="/etc/yum.repos.d.bak"

# 错误处理函数
handle_error() {
echo "Error: $1"
exit 1
}

# 备份现有 YUM 配置文件
backup_yum_config() {
echo "Backing up current YUM configuration files..."
if [ -d "$REPO_DIR" ]; then
mv "$REPO_DIR" "$BACKUP_REPO_DIR" || handle_error "Failed to backup YUM configuration files"
echo "YUM configuration files backed up to $BACKUP_REPO_DIR"
else
echo "No YUM configuration files found to back up"
fi
mkdir -p "$REPO_DIR"
}

# 下载新的镜像源配置文件
download_new_repos() {
echo "Downloading new YUM repository configuration from $NEW_REPO_URL..."
curl -s ${NEW_REPO_URL}/Centos-vault-8.5.2111.repo -o ${REPO_DIR}/Centos-vault-8.5.2111.repo || handle_error "Failed to download Centos-vault-8.5.2111.repo"
curl -s ${NEW_REPO_URL}/epel-archive-8.repo -o ${REPO_DIR}/epel-archive-8.repo || handle_error "Failed to download epel-archive-8.repo"
echo "New YUM repository configuration files downloaded."
}

# 清除 YUM 缓存
clear_yum_cache() {
echo "Clearing YUM cache..."
yum clean all || handle_error "Failed to clean YUM cache"
yum makecache || handle_error "Failed to make YUM cache"
}

# 更新系统
update_system() {
echo "Updating system..."
yum update -y || handle_error "Failed to update system"
}

# 解决 appStream 元数据下载失败问题(可选)
fix_appstream_metadata() {
echo "Fixing appStream metadata download issues..."
for repo_file in $REPO_DIR/CentOS-*; do
if [ -f "$repo_file" ]; then
sudo sed -i -e "s|mirrorlist=|#mirrorlist=|g" "$repo_file"
sudo sed -i -e "s|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g" "$repo_file"
fi
done
echo "AppStream metadata issues fixed."
}

# 主函数
main() {
backup_yum_config
download_new_repos
clear_yum_cache
update_system
fix_appstream_metadata
}

# 执行主函数
main

2. 发送 switch_yum_repo.sh 脚本(可选)

scp switch_yum_repo.sh root@192.168.105.132:/root

3. 赋予脚本可执行权限

chmod +x switch_yum_repo.sh

4. 执行脚本,切换镜像源

./switch_yum_repo.sh

5. 测试是否切换成功

yum update 

// 或者

dnf update

参考资料


亲测CentOS 8.2更换yum源报错Errors during downloading metadata for repository 'epel': - Status code解决办法