26. 巧用Shell条件判断,实现多版本CentOS的yum源自动配置
1. 为什么需要自动配置多版本CentOS的yum源在日常运维工作中我们经常会遇到需要管理不同版本的CentOS服务器的情况。比如有些老项目还在跑CentOS 6新项目则使用CentOS 7甚至有些特殊环境可能需要CentOS 5。每个版本的yum源配置都不相同手动一个个去修改不仅效率低下还容易出错。想象一下这样的场景你手头有50台服务器其中20台是CentOS 7.615台是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}这条命令的执行过程是先读取/etc/redhat-release文件内容使用awk提取第4个字段版本号再用awk以点号分割取前两部分主版本号例如对于CentOS Linux release 7.6.1810 (Core)这条命令会返回7.6。3. 多版本yum源自动配置实战3.1 基础脚本实现让我们先看一个基础版本的多版本yum源配置脚本#!/bin/bash # 定义yum服务器地址 yum_server10.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] namecentos7u6 baseurlftp://$yum_server/centos7u6 gpgcheck0 EOF elif [ $os_version 6.8 ]; then cat /etc/yum.repos.d/centos6u8.repo -EOF [centos6u8] namecentos6u8 baseurlftp://$yum_server/centos6u8 gpgcheck0 EOF elif [ $os_version 5.9 ]; then cat /etc/yum.repos.d/centos5u9.repo -EOF [centos5u9] namecentos5u9 baseurlftp://$yum_server/centos5u9 gpgcheck0 EOF else echo Unsupported CentOS version: $os_version exit 1 fi这个脚本做了以下几件事定义yum服务器地址获取系统主版本号备份原有repo文件根据版本号创建对应的repo文件3.2 脚本优化与增强上面的基础脚本虽然能用但还有很多可以改进的地方。让我们来优化一下#!/bin/bash # 定义yum服务器地址 yum_server10.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] namecentos7u6 baseurlftp://$yum_server/centos7u6 gpgcheck0 repo_filecentos7u6.repo ;; 6.8) repo_content[centos6u8] namecentos6u8 baseurlftp://$yum_server/centos6u8 gpgcheck0 repo_filecentos6u8.repo ;; 5.9) repo_content[centos5u9] namecentos5u9 baseurlftp://$yum_server/centos5u9 gpgcheck0 repo_filecentos5u9.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.优化点包括增加了系统类型检查备份目录加入时间戳避免覆盖使用case语句替代if/elif更清晰增加了yum缓存清理添加了成功提示信息4. 高级技巧与错误处理4.1 网络源与本地源混合配置在实际环境中我们可能需要同时配置网络源和本地源。下面是一个混合配置的示例#!/bin/bash # 定义源地址 network_yum_server10.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] nameLocal Base Repo baseurlfile://${local_yum_server}/base enabled1 gpgcheck0 [local-updates] nameLocal Updates Repo baseurlfile://${local_yum_server}/updates enabled1 gpgcheck0 EOF } # 版本特定配置 case $os_major_version in 7) cat /etc/yum.repos.d/network.repo -EOF [network-base] nameNetwork Base Repo baseurlftp://${network_yum_server}/centos7 enabled1 gpgcheck0 [network-epel] nameNetwork EPEL Repo baseurlftp://${network_yum_server}/epel7 enabled1 gpgcheck0 EOF ;; 6) cat /etc/yum.repos.d/network.repo -EOF [network-base] nameNetwork Base Repo baseurlftp://${network_yum_server}/centos6 enabled1 gpgcheck0 [network-epel] nameNetwork EPEL Repo baseurlftp://${network_yum_server}/epel6 enabled1 gpgcheck0 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] nameCentOS-7.6 - Base baseurlhttp://mirror.centos.org/centos/7.6.1810/os/\$basearch/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 [updates] nameCentOS-7.6 - Updates baseurlhttp://mirror.centos.org/centos/7.6.1810/updates/\$basearch/ gpgcheck1 gpgkeyfile:///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] nameCentOS-6.8 - Base baseurlhttp://vault.centos.org/6.8/os/\$basearch/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 [updates] nameCentOS-6.8 - Updates baseurlhttp://vault.centos.org/6.8/updates/\$basearch/ gpgcheck1 gpgkeyfile:///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 21 || error_exit Failed to clean yum cache yum makecache $LOG_FILE 21 || error_exit Failed to make yum cache log Yum configuration completed successfully这个版本增加了详细的日志记录完善的错误处理root权限检查每个关键步骤的错误检测5. 实际应用案例5.1 批量部署方案当需要在多台服务器上部署时我们可以结合SSH和上面的脚本实现批量部署。下面是一个简单的批量部署方案首先将脚本保存为yum_auto_config.sh并上传到跳板机创建包含所有服务器IP的列表文件server_list.txt使用以下脚本进行批量部署#!/bin/bash # 批量部署yum自动配置脚本 SCRIPT_FILEyum_auto_config.sh SERVER_LISTserver_list.txt SSH_USERroot 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 completed5.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_namecentos 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] nameCentOS-6 - Base baseurlhttps://vault.centos.org/6.10/os/\$basearch/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 [updates] nameCentOS-6 - Updates baseurlhttps://vault.centos.org/6.10/updates/\$basearch/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 EOF ;; 7*) cat /etc/yum.repos.d/CentOS-Base.repo -EOF [base] nameCentOS-7 - Base baseurlhttps://vault.centos.org/7.9.2009/os/\$basearch/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 [updates] nameCentOS-7 - Updates baseurlhttps://vault.centos.org/7.9.2009/updates/\$basearch/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 EOF ;; 8*) cat /etc/yum.repos.d/CentOS-Base.repo -EOF [base] nameCentOS-8 - Base baseurlhttps://vault.centos.org/8.5.2111/BaseOS/\$basearch/os/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial [updates] nameCentOS-8 - Updates baseurlhttps://vault.centos.org/8.5.2111/BaseOS/\$basearch/os/ gpgcheck1 gpgkeyfile:///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] nameCentOS-8 - AppStream baseurlhttps://vault.centos.org/8.5.2111/AppStream/\$basearch/os/ gpgcheck1 gpgkeyfile:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial EOF fi # 清理并重建缓存 yum clean all yum makecache这个脚本的特点支持从CentOS 6到8的版本使用Vault源解决官方源停止维护的问题对于CentOS 8额外配置AppStream源更健壮的系统信息检测方式