26. 巧用Shell条件判断,实现多版本CentOS的yum源自动配置

📅 2026/7/5 12:05:44 👁️ 阅读次数 📝 编程学习
26. 巧用Shell条件判断,实现多版本CentOS的yum源自动配置

1. 为什么需要自动配置多版本CentOS的yum源

在日常运维工作中,我们经常会遇到需要管理不同版本的CentOS服务器的情况。比如有些老项目还在跑CentOS 6,新项目则使用CentOS 7,甚至有些特殊环境可能需要CentOS 5。每个版本的yum源配置都不相同,手动一个个去修改不仅效率低下,还容易出错。

想象一下这样的场景:你手头有50台服务器,其中20台是CentOS 7.6,15台是CentOS 6.8,还有15台是CentOS 5.9。现在需要统一更新yum源配置,如果手动操作,不仅需要记住每个版本对应的源地址,还要确保每台服务器都配置正确。这简直就是运维人员的噩梦!

更糟糕的是,如果配置错误,可能会导致后续的软件安装失败,甚至引发系统问题。我曾经就遇到过因为yum源配置不当,导致系统更新时安装了不兼容的软件包,最后不得不重装系统的惨痛经历。

2. Shell条件判断基础

2.1 if/elif条件结构解析

Shell脚本中的条件判断主要依靠if/elif/else结构来实现。基本语法如下:

if [ 条件1 ]; then # 条件1成立时执行的命令 elif [ 条件2 ]; then # 条件2成立时执行的命令 else # 以上条件都不成立时执行的命令 fi

这里的条件判断使用的是test命令,方括号[ ]实际上是test命令的另一种写法。在比较字符串时,我们使用=号,注意等号两边需要有空格。

2.2 系统版本检测方法

要自动配置yum源,首先需要准确获取当前系统的版本信息。CentOS系统中,版本信息存储在/etc/redhat-release文件中。我们可以使用以下命令提取主版本号:

cat /etc/redhat-release | awk '{print $4}' | awk -F"." '{print $1"."$2}'

这条命令的执行过程是:

  1. 先读取/etc/redhat-release文件内容
  2. 使用awk提取第4个字段(版本号)
  3. 再用awk以点号分割,取前两部分(主版本号)

例如,对于"CentOS Linux release 7.6.1810 (Core)",这条命令会返回"7.6"。

3. 多版本yum源自动配置实战

3.1 基础脚本实现

让我们先看一个基础版本的多版本yum源配置脚本:

#!/bin/bash # 定义yum服务器地址 yum_server="10.18.40.100" # 获取系统主版本号 os_version=$(cat /etc/redhat-release | awk '{print $4}' | awk -F"." '{print $1"."$2}') # 备份原有repo文件 mkdir -p /etc/yum.repos.d/bak mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/ 2>/dev/null # 根据系统版本配置不同的yum源 if [ "$os_version" = "7.6" ]; then cat > /etc/yum.repos.d/centos7u6.repo <<-EOF [centos7u6] name=centos7u6 baseurl=ftp://$yum_server/centos7u6 gpgcheck=0 EOF elif [ "$os_version" = "6.8" ]; then cat > /etc/yum.repos.d/centos6u8.repo <<-EOF [centos6u8] name=centos6u8 baseurl=ftp://$yum_server/centos6u8 gpgcheck=0 EOF elif [ "$os_version" = "5.9" ]; then cat > /etc/yum.repos.d/centos5u9.repo <<-EOF [centos5u9] name=centos5u9 baseurl=ftp://$yum_server/centos5u9 gpgcheck=0 EOF else echo "Unsupported CentOS version: $os_version" exit 1 fi

这个脚本做了以下几件事:

  1. 定义yum服务器地址
  2. 获取系统主版本号
  3. 备份原有repo文件
  4. 根据版本号创建对应的repo文件

3.2 脚本优化与增强

上面的基础脚本虽然能用,但还有很多可以改进的地方。让我们来优化一下:

#!/bin/bash # 定义yum服务器地址 yum_server="10.18.40.100" # 获取系统主版本号 if [ -f /etc/redhat-release ]; then os_version=$(cat /etc/redhat-release | awk '{print $4}' | awk -F"." '{print $1"."$2}') else echo "Not a RedHat/CentOS system" exit 1 fi # 备份原有repo文件 backup_dir="/etc/yum.repos.d/bak_$(date +%Y%m%d%H%M%S)" mkdir -p "$backup_dir" mv /etc/yum.repos.d/*.repo "$backup_dir/" 2>/dev/null # 根据系统版本配置不同的yum源 case "$os_version" in "7.6") repo_content="[centos7u6] name=centos7u6 baseurl=ftp://$yum_server/centos7u6 gpgcheck=0" repo_file="centos7u6.repo" ;; "6.8") repo_content="[centos6u8] name=centos6u8 baseurl=ftp://$yum_server/centos6u8 gpgcheck=0" repo_file="centos6u8.repo" ;; "5.9") repo_content="[centos5u9] name=centos5u9 baseurl=ftp://$yum_server/centos5u9 gpgcheck=0" repo_file="centos5u9.repo" ;; *) echo "Unsupported CentOS version: $os_version" exit 1 ;; esac # 写入repo文件 echo "$repo_content" > "/etc/yum.repos.d/$repo_file" # 清理yum缓存 yum clean all >/dev/null echo "Yum repo for CentOS $os_version has been configured successfully."

优化点包括:

  1. 增加了系统类型检查
  2. 备份目录加入时间戳,避免覆盖
  3. 使用case语句替代if/elif,更清晰
  4. 增加了yum缓存清理
  5. 添加了成功提示信息

4. 高级技巧与错误处理

4.1 网络源与本地源混合配置

在实际环境中,我们可能需要同时配置网络源和本地源。下面是一个混合配置的示例:

#!/bin/bash # 定义源地址 network_yum_server="10.18.40.100" local_yum_server="/mnt/centos" # 获取系统信息 os_version=$(cat /etc/redhat-release | awk '{print $4}' | awk -F"." '{print $1"."$2}') os_major_version=$(echo $os_version | awk -F"." '{print $1}') # 备份原有配置 mkdir -p /etc/yum.repos.d/backup mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ 2>/dev/null # 公共配置部分 common_repo() { cat > /etc/yum.repos.d/local.repo <<-EOF [local-base] name=Local Base Repo baseurl=file://${local_yum_server}/base enabled=1 gpgcheck=0 [local-updates] name=Local Updates Repo baseurl=file://${local_yum_server}/updates enabled=1 gpgcheck=0 EOF } # 版本特定配置 case "$os_major_version" in 7) cat > /etc/yum.repos.d/network.repo <<-EOF [network-base] name=Network Base Repo baseurl=ftp://${network_yum_server}/centos7 enabled=1 gpgcheck=0 [network-epel] name=Network EPEL Repo baseurl=ftp://${network_yum_server}/epel7 enabled=1 gpgcheck=0 EOF ;; 6) cat > /etc/yum.repos.d/network.repo <<-EOF [network-base] name=Network Base Repo baseurl=ftp://${network_yum_server}/centos6 enabled=1 gpgcheck=0 [network-epel] name=Network EPEL Repo baseurl=ftp://${network_yum_server}/epel6 enabled=1 gpgcheck=0 EOF ;; *) echo "Unsupported version: $os_version" exit 1 ;; esac # 调用公共配置 common_repo # 更新yum缓存 yum clean all yum makecache

这个脚本同时配置了本地源和网络源,并且根据主版本号(7或6)配置不同的网络源。

4.2 错误处理与日志记录

一个健壮的脚本应该具备良好的错误处理机制。下面是增加了错误处理和日志记录的版本:

#!/bin/bash # 定义日志文件 LOG_FILE="/var/log/yum_auto_config.log" # 记录日志函数 log() { echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE" } # 错误处理函数 error_exit() { log "ERROR: $1" exit 1 } # 检查root权限 if [ "$(id -u)" != "0" ]; then error_exit "This script must be run as root" fi # 主脚本逻辑 log "Starting yum auto configuration" # 获取系统版本 if [ -f /etc/redhat-release ]; then os_version=$(cat /etc/redhat-release | awk '{print $4}' | awk -F"." '{print $1"."$2}') || \ error_exit "Failed to get OS version" else error_exit "Not a RedHat/CentOS system" fi log "Detected OS version: $os_version" # 备份原有配置 backup_dir="/etc/yum.repos.d/backup_$(date +%Y%m%d)" mkdir -p "$backup_dir" || error_exit "Failed to create backup directory" mv /etc/yum.repos.d/*.repo "$backup_dir/" 2>/dev/null log "Original repo files backed up to $backup_dir" # 配置新源 case "$os_version" in "7.6") log "Configuring for CentOS 7.6" cat > /etc/yum.repos.d/centos7.repo <<-EOF || error_exit "Failed to write repo file" [base] name=CentOS-7.6 - Base baseurl=http://mirror.centos.org/centos/7.6.1810/os/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 [updates] name=CentOS-7.6 - Updates baseurl=http://mirror.centos.org/centos/7.6.1810/updates/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 EOF ;; "6.8") log "Configuring for CentOS 6.8" cat > /etc/yum.repos.d/centos6.repo <<-EOF || error_exit "Failed to write repo file" [base] name=CentOS-6.8 - Base baseurl=http://vault.centos.org/6.8/os/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 [updates] name=CentOS-6.8 - Updates baseurl=http://vault.centos.org/6.8/updates/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 EOF ;; *) error_exit "Unsupported CentOS version: $os_version" ;; esac # 清理并重建缓存 log "Cleaning and rebuilding yum cache" yum clean all >> "$LOG_FILE" 2>&1 || error_exit "Failed to clean yum cache" yum makecache >> "$LOG_FILE" 2>&1 || error_exit "Failed to make yum cache" log "Yum configuration completed successfully"

这个版本增加了:

  1. 详细的日志记录
  2. 完善的错误处理
  3. root权限检查
  4. 每个关键步骤的错误检测

5. 实际应用案例

5.1 批量部署方案

当需要在多台服务器上部署时,我们可以结合SSH和上面的脚本实现批量部署。下面是一个简单的批量部署方案:

  1. 首先将脚本保存为yum_auto_config.sh,并上传到跳板机
  2. 创建包含所有服务器IP的列表文件server_list.txt
  3. 使用以下脚本进行批量部署:
#!/bin/bash # 批量部署yum自动配置脚本 SCRIPT_FILE="yum_auto_config.sh" SERVER_LIST="server_list.txt" SSH_USER="root" SSH_KEY="/root/.ssh/id_rsa" # 检查文件是否存在 [ -f "$SCRIPT_FILE" ] || { echo "Script file $SCRIPT_FILE not found"; exit 1; } [ -f "$SERVER_LIST" ] || { echo "Server list $SERVER_LIST not found"; exit 1; } # 遍历服务器列表 while read -r server; do echo "Processing $server..." # 拷贝脚本到目标服务器 scp -i "$SSH_KEY" "$SCRIPT_FILE" ${SSH_USER}@${server}:/tmp/ || { echo "Failed to copy script to $server" continue } # 在目标服务器执行脚本 ssh -i "$SSH_KEY" ${SSH_USER}@${server} "chmod +x /tmp/$SCRIPT_FILE && /tmp/$SCRIPT_FILE" || { echo "Failed to execute script on $server" continue } echo "$server configured successfully" done < "$SERVER_LIST" echo "Batch configuration completed"

5.2 版本兼容性处理

随着CentOS 8的停止维护和CentOS 7即将停止维护,我们的脚本需要考虑更多版本的兼容性。下面是一个增强版的版本检测和配置逻辑:

#!/bin/bash # 支持更多CentOS版本的yum配置脚本 # 获取详细的系统信息 if [ -f /etc/os-release ]; then source /etc/os-release os_name="$ID" os_version="$VERSION_ID" elif [ -f /etc/redhat-release ]; then os_name="centos" os_version=$(cat /etc/redhat-release | sed -E 's/.*release ([0-9]+).*/\1/') else echo "Unsupported OS" exit 1 fi # 检查是否是CentOS系统 if [ "$os_name" != "centos" ]; then echo "This script only supports CentOS" exit 1 fi # 备份原有配置 mkdir -p /etc/yum.repos.d/backup mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ 2>/dev/null # 配置Vault源(适用于CentOS 6/7/8) case "$os_version" in 5*) echo "CentOS 5 is too old and not supported" exit 1 ;; 6*) cat > /etc/yum.repos.d/CentOS-Base.repo <<-EOF [base] name=CentOS-6 - Base baseurl=https://vault.centos.org/6.10/os/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 [updates] name=CentOS-6 - Updates baseurl=https://vault.centos.org/6.10/updates/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 EOF ;; 7*) cat > /etc/yum.repos.d/CentOS-Base.repo <<-EOF [base] name=CentOS-7 - Base baseurl=https://vault.centos.org/7.9.2009/os/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 [updates] name=CentOS-7 - Updates baseurl=https://vault.centos.org/7.9.2009/updates/\$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 EOF ;; 8*) cat > /etc/yum.repos.d/CentOS-Base.repo <<-EOF [base] name=CentOS-8 - Base baseurl=https://vault.centos.org/8.5.2111/BaseOS/\$basearch/os/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial [updates] name=CentOS-8 - Updates baseurl=https://vault.centos.org/8.5.2111/BaseOS/\$basearch/os/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial EOF ;; *) echo "Unsupported CentOS version: $os_version" exit 1 ;; esac # 对于CentOS 8+,还需要配置AppStream if [[ "$os_version" =~ ^8 ]]; then cat > /etc/yum.repos.d/CentOS-AppStream.repo <<-EOF [appstream] name=CentOS-8 - AppStream baseurl=https://vault.centos.org/8.5.2111/AppStream/\$basearch/os/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial EOF fi # 清理并重建缓存 yum clean all yum makecache

这个脚本的特点:

  1. 支持从CentOS 6到8的版本
  2. 使用Vault源,解决官方源停止维护的问题
  3. 对于CentOS 8+,额外配置AppStream源
  4. 更健壮的系统信息检测方式