yum 命令详解与参数实测(CentOS 7.9)

以 CentOS 7.9(yum 3.4.3-168)实测逐项讲解 yum:install/remove/update/downgrade/check-update/search/info/list/provides/repolist/makecache/clean/history/autoremove/group 等子命令与 -y/-q/-v/--showduplicates/--downloadonly/--installroot/--enablerepo 等参数的真实回显,覆盖 EOL 后软件源修复与 GPG/依赖/缓存等常见故障排障。

Linux命令Linux系统CentOS命令行包管理2026/10/17

yum 命令详解与参数实测(CentOS 7.9)

目标:全面掌握 yum 的每一个常用子命令与全局选项——install/remove/update/downgrade 装卸升降级、check-update 只查不装、search/info/list/provides 查询四件套、repolist/makecache/clean 软件源与缓存管理、history undo/redo 事务回滚、autoremove 孤儿依赖清理、group 组管理,以及 -y/-q/-v/--showduplicates/--downloadonly/--installroot/--enablerepo/--disablerepo 等参数,全部命令与回显已在 CentOS Linux 7.9.2009(yum 3.4.3-168)实测通过;并完整收录 CentOS 7 EOL 后官方软件源失效的故障实录、定位与两种修复方案。

一、环境信息

本文所有命令均在以下环境实测,回显逐字照抄:

  • 操作系统:CentOS Linux 7 (Core)(/etc/centos-release 实测为 CentOS Linux release 7.9.2009 (Core))
  • 内核架构:x86_64(uname -m 实测)
  • yum 版本:3.4.3-168.el7.centos.noarch(yum 3.4.3 系列,CentOS 7 最终版)
  • 底层 rpm:rpm-4.11.3-45.el7.x86_64
  • 配套插件:yum-plugin-fastestmirror-1.1.31-54.el7_8.noarch(自动选最快软件源)
  • 下载器组件:python-urlgrabber-3.10-10.el7.noarch
  • 执行身份:root
  • 软件源:base/updates/extras(阿里云 CentOS 7.9.2009 归档)+ epel(阿里云 EPEL 7 归档),修复过程见 2.4
  • 演示软件包:tree 1.6.0-10.el7(base 源)、sl 5.02-1.el7(epel 源)、geoipupdate 2.5.0-x(updates 源)、vim-enhanced 及依赖链、zsh、lsscsi

💡 说明:CentOS 7 已于 2024-06-30 停止维护(EOL),官方 mirrorlist.centos.org 域名已停止解析、官方软件源已下线。本文在全新安装形态的系统上从「原始报错」开始实测,先把软件源修复到可用,再逐项验证 yum 各参数——这也是目前任何一台仍在服役的 CentOS 7 机器都要走的第一步。

二、命令概览

2.1 语法形态与子命令总览

yum 是 RHEL/CentOS 系的 RPM 包管理器前端,负责自动解决软件包之间的依赖关系,从配置好的软件源下载并安装/升级/卸载 RPM 包。实测 yum --help 给出的语法只有一行:

Usage: yum [options] COMMAND

即「全局选项 + 子命令(+ 子命令参数)」两部分。全局选项(如 -y、--enablerepo)写在子命令前后均可生效;子命令决定动作。按用途把 --help 中的 28 个子命令分组如下(分组为本文归纳,原文见 2.2):

分组子命令用途
安装卸载install、remove/erase、reinstall、downgrade、swap、localinstall(历史别名)装包、卸包、重装、降级、一换一
升级更新update、upgrade、update-minimal、distribution-synchronization、check-update升级(全量/定点)、最小安全更新、只查不装
查询检索list、info、search、provides、deplist、version清单、详情、搜索、反查文件归属、依赖清单
软件源repolist、makecache、clean、repo-pkgs、updateinfo源清单、建缓存、清缓存、按源批量操作
事务历史history、load-transaction事务列表/详情/撤销/重放、载入已保存事务
组管理group/groups包组查看与安装卸载
交互诊断shell、check、fs、fssnapshot、help交互模式、rpmdb 体检、文件系统瘦身

💡 说明:yum 3.4.3 的 yum --help 列表中并没有 autoremove,但在 CentOS 7.9 的 yum-3.4.3-168 上直接可用(实测见 3.13),早期 7.x 版本需要安装 yum-plugin-autoremove 插件才有该命令——同一个「yum」在不同小版本上能力有差异,排障时先确认 yum --version。

2.2 --help 全量输出(逐行照抄)

先看完整帮助,是逐参数实测的地图。以下为 yum --help 的完整实测输出:

$ yum --help
Loaded plugins: fastestmirror, ovl
Usage: yum [options] COMMAND

List of Commands:

check          Check for problems in the rpmdb
check-update   Check for available package updates
clean          Remove cached data
deplist        List a package's dependencies
distribution-synchronization Synchronize installed packages to the latest available versions
downgrade      downgrade a package
erase          Remove a package or packages from your system
fs             Acts on the filesystem data of the host, mainly for removing docs/lanuages for minimal hosts.
fssnapshot     Creates filesystem snapshots, or lists/deletes current snapshots.
groups         Display, or use, the groups information
help           Display a helpful usage message
history        Display, or use, the transaction history
info           Display details about a package or group of packages
install        Install a package or packages on your system
list           List a package or groups of packages
load-transaction load a saved transaction from filename
makecache      Generate the metadata cache
provides       Find what package provides the given value
reinstall      reinstall a package
repo-pkgs      Treat a repo. as a group of packages, so we can install/remove all of them
repolist       Display the configured software repositories
search         Search package details for the given string
shell          Run an interactive yum shell
swap           Simple way to swap packages, instead of using shell
update         Update a package or packages on your system
update-minimal Works like upgrade, but goes to the 'newest' package match which fixes a problem that affects your system
updateinfo     Acts on repository update information
upgrade        Update packages taking obsoletes into account
version        Display a version for the machine and/or available repos.


Options:
  -h, --help            show this help message and exit
  -t, --tolerant        be tolerant of errors
  -C, --cacheonly       run entirely from system cache, don't update cache
  -c [config file], --config=[config file]
                        config file location
  -R [minutes], --randomwait=[minutes]
                        maximum command wait time
  --showduplicates      show duplicates, in repos, in list/search commands
  -e [error level], --errorlevel=[error level]
                        error output level
  --rpmverbosity=[debug level name]
                        debugging output level for rpm
  -q, --quiet           quiet operation
  -v, --verbose         verbose operation
  -y, --assumeyes       answer yes for all questions
  --assumeno            answer no for all questions
  --version             show Yum version and exit
  --installroot=[path]  set install root
  --enablerepo=[repo]   enable one or more repositories (wildcards allowed)
  --disablerepo=[repo]  disable one or more repositories (wildcards allowed)
  -x [package], --exclude=[package]
                        exclude package(s) by name or glob
  --disableexcludes=[repo]
                        disable exclude from main, for a repo or for
                        everything
  --disableincludes=[repo]
                        disable includepkgs for a repo or for everything
  --obsoletes           enable obsoletes processing during updates
  --noplugins           disable Yum plugins
  --nogpgcheck          disable gpg signature checking
  --disableplugin=[plugin]
                        disable plugins by name
  --enableplugin=[plugin]
                        enable plugins by name
  --skip-broken         skip packages with depsolving problems
  --color=COLOR         control whether color is used
  --releasever=RELEASEVER
                        set value of $releasever in yum config and repo files
  --downloadonly        don't update, just download
  --downloaddir=DLDIR   specifies an alternate directory to store packages
  --setopt=SETOPTS      set arbitrary config and repo options
  --bugfix              Include bugfix relevant packages, in updates
  --security            Include security relevant packages, in updates
  --advisory=ADVS, --advisories=ADVS
                        Include packages needed to fix the given advisory, in
                        updates
  --bzs=BZS             Include packages needed to fix the given BZ, in
                        updates
  --cves=CVES           Include packages needed to fix the given CVE, in
                        updates
  --sec-severity=SEVS, --secseverity=SEVS
                        Include security relevant packages matching the
                        severity, in updates

  Plugin Options:

关键解读:Plugin Options: 之后为空——本机装载的 fastestmirror、ovl 两个插件都没有注册命令行专属选项;-y 与 --assumeno 互斥(一个全答 yes、一个全答 no);--obsoletes 单独出现说明 update 默认不处理废弃包,而 upgrade 子命令(见 3.3)等价于 update --obsoletes;--showduplicates、--downloadonly、--installroot、--setopt 这些高频运维选项均为内置,无需装插件。

2.3 版本信息

yum 自带 --version 选项,除自身版本外还会列出 rpm 与已装插件的版本(这是 yum 3.4.3 的特殊行为,输出的是一串组件清单而不是单个版本号):

$ yum --version
3.4.3
  Installed: rpm-4.11.3-45.el7.x86_64 at 2020-11-13 01:54
  Built    : CentOS BuildSystem <http://bugs.centos.org> at 2020-09-30 17:30
  Committed: Michal Domonkos <mdomonko@redhat.com> at 2020-06-02

  Installed: yum-3.4.3-168.el7.centos.noarch at 2020-11-13 01:54
  Built    : CentOS BuildSystem <http://bugs.centos.org> at 2020-10-01 17:03
  Committed: CentOS Sources <bugs@centos.org> at 2020-09-29

  Installed: yum-plugin-fastestmirror-1.1.31-54.el7_8.noarch at 2020-11-13 01:54
  Built    : CentOS BuildSystem <http://bugs.centos.org> at 2020-05-12 16:27
  Committed: Michal Domonkos <mdomonko@redhat.com> at 2020-03-12

用 rpm 复核关键组件版本,与上面对应:

$ rpm -q yum yum-plugin-fastestmirror rpm python-urlgrabber
yum-3.4.3-168.el7.centos.noarch
yum-plugin-fastestmirror-1.1.31-54.el7_8.noarch
rpm-4.11.3-45.el7.x86_64
python-urlgrabber-3.10-10.el7.noarch

结论:yum 主版本 3.4.3、构建号 168(el7 最终版);centos-release 提供的系统版本为 7.9.2009。本文全部结论基于该版本。

2.4 测试数据准备与软件源修复(CentOS 7 EOL 实录)

yum 的所有子命令都依赖软件源(repo)可用,因此先把一台「原始状态」的 CentOS 7.9 的软件源从故障修复到可用,后续 3.x 节的所有实测都在修复后的源上执行。

2.4.1 原始状态与故障实录

全新安装的 CentOS 7.9 的软件源定义在 /etc/yum.repos.d/ 下,共 8 个 repo 文件,全部以 mirrorlist=(动态站点列表)方式指向 mirrorlist.centos.org:

$ ls -l /etc/yum.repos.d/
total 40
-rw-r--r-- 1 root root 1664 Oct 23  2020 CentOS-Base.repo
-rw-r--r-- 1 root root 1309 Oct 23  2020 CentOS-CR.repo
-rw-r--r-- 1 root root  649 Oct 23  2020 CentOS-Debuginfo.repo
-rw-r--r-- 1 root root  630 Oct 23  2020 CentOS-Media.repo
-rw-r--r-- 1 root root 1331 Oct 23  2020 CentOS-Sources.repo
-rw-r--r-- 1 root root 8515 Oct 23  2020 CentOS-Vault.repo
-rw-r--r-- 1 root root  314 Oct 23  2020 CentOS-fasttrack.repo
-rw-r--r-- 1 root root  616 Oct 23  2020 CentOS-x86_64-kernel.repo

CentOS-Base.repo 原始内容(逐行照抄,重点看每个小节的 mirrorlist= 行):

# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#

[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#released updates
[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

EOL 之后 mirrorlist.centos.org 已停止解析。先用 DNS 与 HTTP 两个层面取证:

$ getent hosts mirrorlist.centos.org; echo "getent 退出码=$?"
getent 退出码=2

$ curl -sS -m 15 "http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=stock"; echo "curl 退出码=$?"
curl: (6) Could not resolve host: mirrorlist.centos.org; Unknown error
curl 退出码=6

域名级故障(getent 退出码 2 = 未找到记录)传导到 yum 层面,yum repolist 的真实输出:

$ yum repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=stock error was
14: curl#6 - "Could not resolve host: mirrorlist.centos.org; Unknown error"
Loading mirror speeds from cached hostfile
Loading mirror speeds from cached hostfile
Loading mirror speeds from cached hostfile
repo id                             repo name                             status
base/7/x86_64                       CentOS-7 - Base                       0
extras/7/x86_64                     CentOS-7 - Extras                     0
updates/7/x86_64                    CentOS-7 - Updates                    0
repolist: 0

需要真正下载元数据的命令(如 yum makecache)则直接失败,yum 给出完整的自救指引与最终错误:

$ yum makecache
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=stock error was
14: curl#6 - "Could not resolve host: mirrorlist.centos.org; Unknown error"


 One of the configured repositories failed (Unknown),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=<repoid> ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable <repoid>
        or
            subscription-manager repos --disable=<repoid>

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

Cannot find a valid baseurl for repo: base/7/x86_64

💡 说明:repolist: 0 与退出码现象值得注意——yum repolist 在 mirrorlist 失败时仍返回 0(它只展示已缓存的源列表,条目数全为 0);yum makecache 则返回退出码 1 并报 Cannot find a valid baseurl for repo: base/7/x86_64。mirrorlist URL 中的 $releasever(值 7,来自 centos-release 包)、$basearch(x86_64)、$infra(/etc/yum/vars/infra 文件内容,标准安装为 stock)都是 yum 的配置变量,修复时改 baseurl 也要考虑 $releasever=7 与归档路径 7.9.2009 不一致的问题。

2.4.2 归档软件源可用性探测

CentOS 7 EOL 后官方把全部历史包移入归档。先探测各候选归档路径的 HTTP 状态码,再决定 baseurl 怎么写(curl -w '%{http_code}' 只取状态码):

200  http://mirrors.aliyun.com/centos-vault/7.9.2009/os/x86_64/
200  http://mirrors.aliyun.com/centos-vault/centos/7.9.2009/os/x86_64/
200  http://mirrors.aliyun.com/centos/7.9.2009/os/x86_64/
403  https://vault.centos.org/7.9.2009/os/x86_64/
200  http://mirrors.aliyun.com/centos-vault/7.9.2009/updates/x86_64/
200  http://mirrors.aliyun.com/centos-vault/7.9.2009/extras/x86_64/

结论:阿里云归档(mirrors.aliyun.com/centos-vault/7.9.2009/...)全路径 200 可用;官方归档 vault.centos.org 从本网络实测返回 403(部分网络/地区被拒绝,与网上反馈一致),因此采用阿里云归档作为修复目标。

💡 技术拓展:repo 定址机制不止 mirrorlist 一种,常见三种对比——

机制原理现状(CentOS 7)
mirrorlist=运行时请求列表服务,返回当前可用站点mirrorlist.centos.org 已停止解析,失效
metalink=同为运行时列表服务,附校验信息(EPEL 使用)mirrors.fedoraproject.org 仍返回 EPEL 7 归档站点,但个别站点 TLS 不兼容,不稳定
baseurl=固定 URL,直接指向源根目录指向归档站后长期稳定,EOL 环境首选

本文实际采用 baseurl 固定指向阿里云归档:EOL 系统的包集合已冻结,不再需要 mirrorlist 的「动态选快」能力,固定 URL 反而消除了运行时列表服务这个单点。

2.4.3 修复方案 A:备份原 repo 并新写归档 repo(推荐)

第一步,把原始 repo 文件整体备份移走(备份目录不以 .repo 结尾,yum 不会读取):

$ mkdir -p /etc/yum.repos.d/backup
$ mv /etc/yum.repos.d/CentOS-*.repo /etc/yum.repos.d/backup/
$ ls -l /etc/yum.repos.d/ /etc/yum.repos.d/backup/
/etc/yum.repos.d/:
total 4
drwxr-xr-x 2 root root 4096 Oct 16 16:21 backup

/etc/yum.repos.d/backup/:
total 40
-rw-r--r-- 1 root root 1664 Oct 23  2020 CentOS-Base.repo
-rw-r--r-- 1 root root 1309 Oct 23  2020 CentOS-CR.repo
-rw-r--r-- 1 root root  649 Oct 23  2020 CentOS-Debuginfo.repo
-rw-r--r-- 1 root root  630 Oct 23  2020 CentOS-Media.repo
-rw-r--r-- 1 root root 1331 Oct 23  2020 CentOS-Sources.repo
-rw-r--r-- 1 root root 8515 Oct 23  2020 CentOS-Vault.repo
-rw-r--r-- 1 root root  314 Oct 23  2020 CentOS-fasttrack.repo
-rw-r--r-- 1 root root  616 Oct 23  2020 CentOS-x86_64-kernel.repo

确认 GPG 公钥文件仍在(gpgcheck=1 需要它验签):

$ ls -l /etc/pki/rpm-gpg/
total 12
-rw-r--r-- 1 root root 1690 Oct 23  2020 RPM-GPG-KEY-CentOS-7
-rw-r--r-- 1 root root 1004 Oct 23  2020 RPM-GPG-KEY-CentOS-Debug-7
-rw-r--r-- 1 root root 1690 Oct 23  2020 RPM-GPG-KEY-CentOS-Testing-7

写入新的 CentOS-Base.repo,三个启用小节(base/updates/extras)全部固定到阿里云归档的 7.9.2009 目录(归档路径用具体小版本号,不能用 $releasever——它的值是 7):

cat > /etc/yum.repos.d/CentOS-Base.repo <<'EOF'
# CentOS-7.9.2009 阿里云归档软件源(CentOS 7 EOL 后官方源已下线,改用归档)
[base]
name=CentOS-7.9.2009 - Base
baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/os/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[updates]
name=CentOS-7.9.2009 - Updates
baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/updates/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[extras]
name=CentOS-7.9.2009 - Extras
baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/extras/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1
EOF

清缓存 → 重建缓存 → 验证,全链路成功回显:

$ yum clean all
Loaded plugins: fastestmirror, ovl
Cleaning repos: base extras updates
Cleaning up list of fastest mirrors

$ yum makecache
Loaded plugins: fastestmirror, ovl
Determining fastest mirrors
Metadata Cache Created

$ yum repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id                     repo name                                     status
base                        CentOS-7.9.2009 - Base                        10072
extras                      CentOS-7.9.2009 - Extras                        526
updates                     CentOS-7.9.2009 - Updates                      6173
repolist: 16771

base 10072 + updates 6173 + extras 526 = 16771 个包可用,软件源修复完成。

2.4.4 修复方案 B:sed 批改原 repo 文件

不想新写文件的话,可以把备份的原文件恢复回来后用 sed 原地批改:注释所有 mirrorlist= 行,同时把被注释的 #baseurl=http://mirror.centos.org/centos/$releasever 替换为启用状态的阿里云归档 URL:

cp /etc/yum.repos.d/backup/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo
sed -i \
  -e 's|^mirrorlist=|#mirrorlist=|' \
  -e 's|^#baseurl=http://mirror.centos.org/centos/\$releasever|baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009|' \
  /etc/yum.repos.d/CentOS-Base.repo

批改后 grep 复核(mirrorlist 已注释、baseurl 已启用;os/updates/extras 子路径由原文件 #baseurl= 行的 /$releasever 后半段拼接而来,默认禁用的 [centosplus] 小节的 baseurl 也被同一模式命中改写,但其 enabled=0 不生效):

$ grep -nE '#mirrorlist=|^baseurl=' /etc/yum.repos.d/CentOS-Base.repo
15:#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
16:baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/os/$basearch/
23:#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
24:baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/updates/$basearch/
31:#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
32:baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/extras/$basearch/
39:#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
40:baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/centosplus/$basearch/

同样验证通过(yum clean all && yum makecache 后 repolist 16771):

$ yum repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id                            repo name                              status
base/x86_64                        CentOS-7 - Base                        10072
extras/x86_64                      CentOS-7 - Extras                        526
updates/x86_64                     CentOS-7 - Updates                      6173
repolist: 16771

两种方案等效:方案 A 配置干净可读,方案 B 保留原文件结构与注释;repo id 显示样式(base 与 base/x86_64)与 repo 文件中是否保留 $releasever 变量定义有关,不影响使用。本文最终采用方案 A 的干净配置继续后续实测。

2.4.5 EPEL 软件源安装与修复

很多常用小工具(如 3.1 之后的演示包 sl)在 EPEL 源里。epel-release 包由 CentOS extras 源提供,直接安装:

$ yum install -y epel-release
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-11 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package                Arch             Version         Repository        Size
================================================================================
Installing:
 epel-release           noarch           7-11            extras            15 k

Transaction Summary
================================================================================
Install  1 Package

Total download size: 15 k
Installed size: 24 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : epel-release-7-11.noarch                                     1/1
  Verifying  : epel-release-7-11.noarch                                     1/1

Installed:
  epel-release.noarch 0:7-11

Complete!

epel-release 装的是 /etc/yum.repos.d/epel.repo(及 epel-testing.repo),其 [epel] 小节同样用 metalink 动态定址:

[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

EPEL 7 同样已归档:metalink 服务仍能返回归档站点列表,但个别归档站点与新版 TLS 握手不兼容(老 NSS 报协议错误),实测 repolist 时出现过这样的报错后「Trying other mirror」才成功:

 * epel: d2lzkl7pfhq30w.cloudfront.net
https://fedora-archive.ip-connect.vn.ua/epel/7/x86_64/repodata/ee7ce72544e0fca006120c613404d937cc3da9d09c7d80aea269df31639f310c-updateinfo.xml.bz2: [Errno 14] curl#35 - "Peer reports incompatible or unsupported protocol version."
Trying other mirror.

为消除这种「碰运气」,同样用 sed 固定 baseurl 到阿里云 EPEL 归档(探测确认 http://mirrors.aliyun.com/epel-archive/7/x86_64/ 返回 200,mirrors.fedoraproject.org 的 metalink 也返回 200 但内容不稳定):

sed -i \
  -e 's|^metalink=|#metalink=|' \
  -e 's|^mirrorlist=|#mirrorlist=|' \
  -e 's|^#baseurl=http://download.fedoraproject.org/pub/epel/7/\$basearch|baseurl=http://mirrors.aliyun.com/epel-archive/7/x86_64|' \
  /etc/yum.repos.d/epel.repo

修复后的 [epel] 小节(epel-debuginfo 等禁用小节同法处理,源码小节保持注释即可):

[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel-archive/7/x86_64
#metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

重建缓存后四源齐备:

$ yum repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id          repo name                                                status
base             CentOS-7.9.2009 - Base                                   10072
epel             Extra Packages for Enterprise Linux 7 - x86_64           13791
extras           CentOS-7.9.2009 - Extras                                   526
updates          CentOS-7.9.2009 - Updates                                 6173
repolist: 30562

💡 说明:EPEL 归档路径是 epel-archive(不是 epel),这是阿里云在 EPEL 7 EOL 后专门开辟的归档目录;yum clean all && yum makecache 是每次改完 repo 文件后的固定两连,改配置不生效时先想它。

三、参数逐项实测

3.1 install:安装软件包(含 -y 与 GPG 密钥首次导入)

install 按包名从软件源解析依赖、下载并安装 RPM。-y(--assumeyes)对所有「Is this ok [y/N]:」确认自动回答 yes,脚本环境必备。以 46KB 的 tree 为例,完整事务回显如下(首次从 base 源装包时顺带完成了 CentOS GPG 公钥导入):

$ yum install -y tree
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package tree.x86_64 0:1.6.0-10.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package        Arch             Version                   Repository      Size
================================================================================
Installing:
 tree           x86_64           1.6.0-10.el7              base            46 k

Transaction Summary
================================================================================
Install  1 Package

Total download size: 46 k
Installed size: 87 k
Downloading packages:
warning: /var/cache/yum/x86_64/7/base/packages/tree-1.6.0-10.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Public key for tree-1.6.0-10.el7.x86_64.rpm is not installed
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>"
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 Package    : centos-release-7-9.2009.0.el7.centos.x86_64 (@CentOS)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : tree-1.6.0-10.el7.x86_64                                     1/1
  Verifying  : tree-1.6.0-10.el7.x86_64                                     1/1

Installed:
  tree.x86_64 0:1.6.0-10.el7

Complete!

安装后三重复核(rpmdb、二进制版本、info):

$ rpm -q tree
tree-1.6.0-10.el7.x86_64

$ tree --version
tree v1.6.0 (c) 1996 - 2011 by Steve Baker, Thomas Moore, Francesc Rocher, Kyosuke Tokoro

重复安装同一个包,yum 明确告知无需操作而非报错(退出码仍为 0):

$ yum install -y tree
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Package tree-1.6.0-10.el7.x86_64 already installed and latest version
Nothing to do

💡 要点:

  1. NOKEY 警告与 GPG 导入是一次性正常流程:gpgcheck=1 时 rpm 包头部签名需要公钥验证,首次遇到某源的包会自动从 gpgkey= 指向的本地文件导入并展示指纹(CentOS-7 Key f4a80eb5、EPEL-7 Key 352c64e5 都在本文实测中出现过),导入一次后不再出现;若指纹与官方公布不符必须中止。
  2. -y 省略时会发生什么:不带 -y 的安装/卸载/autoremove 会在「Is this ok [y/N]:」处停住等输入;在无交互的脚本里会以 Exiting on user command 退出、退出码 1,并把未执行的事务存到 /tmp/yum_save_tx.*.yumtx 提示可用 yum load-transaction 重放(3.13 实测)。
  3. 事务回显有固定五段结构:依赖解析(Resolving/Running transaction check)→ 事务表(Dependencies Resolved)→ 汇总(Transaction Summary)→ 下载 → 执行与校验(Installing/Verifying + Complete!),读懂这张表就能确认「装了什么、来自哪个源、占多大空间」。

3.2 remove / erase:卸载与依赖遗留

remove 卸载指定包及其仅因它而被拉入的依赖(依赖若被其他包需要则保留)。erase 是 remove 的完全等价别名。实测先装回 tree 再卸载:

$ yum remove -y tree
Loaded plugins: fastestmirror, ovl
Resolving Dependencies
--> Running transaction check
---> Package tree.x86_64 0:1.6.0-10.el7 will be erased
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package        Arch             Version                   Repository      Size
================================================================================
Removing:
 tree           x86_64           1.6.0-10.el7             @base            87 k

Transaction Summary
================================================================================
Remove  1 Package

Installed size: 87 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Erasing    : tree-1.6.0-10.el7.x86_64                                     1/1
  Verifying  : tree-1.6.0-10.el7.x86_64                                     1/1

Removed:
  tree.x86_64 0:1.6.0-10.el7

Complete!
$ rpm -q tree
package tree is not installed

注意事务表里 Repository 列显示 @base——@ 前缀表示该包已安装、来自 base 源(卸载和删除场景显示的都是 @来源)。卸载一个不存在的包则只是两行提示、正常返回(实测退出码 0):

$ yum remove -y zsh
Loaded plugins: fastestmirror, ovl
No Match for argument: zsh
No Packages marked for removal

💡 要点:remove 不会顺带清掉「没有别的包再需要」的历史依赖——依赖包会留在系统里(标记为 dep 原因),需要 yum autoremove 二段式清理,完整闭环见 3.13;只想删配置文件连存档都不留时用 yum remove 后手工 rm -rf 配置目录,yum 没有 apt 的 purge 语义。

3.3 update 与 upgrade:升级(含两者关系)

update 把指定包(不给包名则全量)升级到软件源中的最新版本。先看演示包 geoipupdate 有哪些版本可升——installed 是 2.5.0-1(来自装机时的源),base 源里也是 2.5.0-1,updates 源里有 2.5.0-2:

$ yum list --showduplicates geoipupdate
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Installed Packages
geoipupdate.x86_64                      2.5.0-1.el7                      @CentOS
Available Packages
geoipupdate.x86_64                      2.5.0-1.el7                      base
geoipupdate.x86_64                      2.5.0-2.el7                      updates

定点升级到 2.5.0-2(完整回显,注意事务表的 Updating 与执行段的 Updating/Cleanup 成对出现):

$ yum update -y geoipupdate
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package geoipupdate.x86_64 0:2.5.0-1.el7 will be updated
---> Package geoipupdate.x86_64 0:2.5.0-2.el7 will be an update
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package             Arch           Version               Repository       Size
================================================================================
Updating:
 geoipupdate         x86_64         2.5.0-2.el7           updates          35 k

Transaction Summary
================================================================================
Upgrade  1 Package

Total download size: 35 k
Downloading packages:
Delta RPMs disabled because /usr/bin/applydeltarpm not installed.
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Updating   : geoipupdate-2.5.0-2.el7.x86_64                               1/2
  Cleanup    : geoipupdate-2.5.0-1.el7.x86_64                               2/2
  Verifying  : geoipupdate-2.5.0-2.el7.x86_64                               1/2
  Verifying  : geoipupdate-2.5.0-1.el7.x86_64                               2/2

Updated:
  geoipupdate.x86_64 0:2.5.0-2.el7

Complete!
$ rpm -q geoipupdate
geoipupdate-2.5.0-2.el7.x86_64

升级后 yum check-update 对该包返回 0(3.5 详解退出码):

$ yum -q check-update geoipupdate
$ echo $?
0

upgrade 子命令的实测输出与 update 完全同构(同包升级事务、Upgrade 1 Package 汇总、Updating/Cleanup 执行段),此处不再重复贴全文。两者的关系在 --help 原文里写得很直白:upgrade Update packages taking obsoletes into account——upgrade = update --obsoletes,即在升级时额外处理「废弃替代」关系(包 A 被官方废弃、由包 B 取代时,update 不动它,upgrade 会用 B 替换 A)。CentOS 7 的 /etc/yum.conf 默认 obsoletes=1,所以日常两者几乎无差别。

💡 要点:

  1. Delta RPMs disabled because /usr/bin/applydeltarpm not installed. 是常见提示:源里有 deltarpm(差量包)可省流量,但系统没装 applydeltarpm 工具就整包下载,装上 presto/deltarpm 插件才启用,通常无需理会。
  2. Updating(装新版)与 Cleanup(清旧版)总是成对出现,行数是「2/2」这类两步计数,这不是装了两遍。
  3. 生产升级铁律:内核、glibc、openssl 这类基础件升级后必须重启或重启对应服务才真正生效,yum update 成功 ≠ 已生效。

3.4 downgrade:降级

downgrade 把包降回软件源中比当前版本低的最高可用版本。geoipupdate 刚升到 2.5.0-2,base 源还保留着 GA 版 2.5.0-1,正好演示:

$ yum downgrade -y geoipupdate
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package geoipupdate.x86_64 0:2.5.0-1.el7 will be a downgrade
---> Package geoipupdate.x86_64 0:2.5.0-2.el7 will be erased
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package              Arch            Version               Repository     Size
================================================================================
Downgrading:
 geoipupdate          x86_64          2.5.0-1.el7           base           35 k

Transaction Summary
================================================================================
Downgrade  1 Package

Total download size: 35 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : geoipupdate-2.5.0-1.el7.x86_64                               1/2
  Cleanup    : geoipupdate-2.5.0-2.el7.x86_64                               2/2
  Verifying  : geoipupdate-2.5.0-1.el7.x86_64                               1/2
  Verifying  : geoipupdate-2.5.0-2.el7.x86_64                               2/2

Removed:
  geoipupdate.x86_64 0:2.5.0-2.el7

Installed:
  geoipupdate.x86_64 0:2.5.0-1.el7

Complete!
$ rpm -q geoipupdate
geoipupdate-2.5.0-1.el7.x86_64

💡 要点:downgrade 的前提是旧版本仍在某个启用的源里。常规在线软件源只保留每个包的最新版,旧版一升级就被顶掉,此时 downgrade 会报 Only Upgrade available on package ...;本文能降回去,正是因为归档源(centos-vault 的 os 目录 = 7.9.2009 GA 版)天然保留了历史版本——这是 EOL 归档源除「能用」之外的另一个价值。更可靠的回滚手段是 3.12 的 history undo。

3.5 check-update:只检查不更新(退出码 100)

check-update 列出所有可用更新但不做任何改动,专为脚本巡检设计。本机(装机于 7.9.2009 GA 时点)相对最终版 updates 源有 51 个包可升,实测输出节选:

$ yum check-update
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile

bash.x86_64                        4.2.46-35.el7_9                       updates
bind-license.noarch                32:9.11.4-26.P2.el7_9.16              updates
binutils.x86_64                    2.27-44.base.el7_9.1                  updates
ca-certificates.noarch             2023.2.60_v7.0.306-72.el7_9           updates
centos-release.x86_64              7-9.2009.2.el7.centos                 updates
coreutils.x86_64                   8.22-24.el7_9.2                       updates
curl.x86_64                        7.29.0-59.el7_9.2                     updates
...
tzdata.noarch                      2024a-1.el7                           updates
util-linux.x86_64                  2.23.2-65.el7_9.1                     updates
vim-minimal.x86_64                 2:7.4.629-8.el7_9                     updates
xz.x86_64                          5.2.2-2.el7_9                         updates
xz-libs.x86_64                     5.2.2-2.el7_9                         updates
zlib.x86_64                        1.2.7-21.el7_9                        updates
(输出节选:51 个包,实测首尾)

退出码是本命令的灵魂,实测三种取值:

$ yum check-update >/dev/null 2>&1; echo $?
100        ← 有可用更新
$ yum -q check-update geoipupdate; echo $?   (3.3 已升到最新)
0          ← 无可用更新

💡 要点:退出码约定为 0 = 无更新、100 = 有更新、1 = 出错(元数据/网络故障)。监控脚本用「rc == 100 才告警或触发升级」判断,比解析 stdout 稳得多;check-update 后紧跟 yum update -y --security 可以做「只装安全补丁」的定期任务(--security 依据源的 updateinfo 元数据筛选)。

3.6 search:按关键词搜索包

search 在包名与摘要(默认)中匹配关键词,输出「包名 : 一句话描述」:

$ yum search tree
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
============================== N/S matched: tree ===============================
gomtree.x86_64 : Go CLI tool for mtree support
maven-dependency-tree.noarch : Maven dependency tree artifact
maven-dependency-tree-javadoc.noarch : Javadoc for maven-dependency-tree
ostree.x86_64 : Tool for managing bootable, immutable filesystem trees
ostree-devel.x86_64 : Development headers for ostree
ostree-fuse.x86_64 : FUSE utilities for ostree
ostree-grub2.x86_64 : GRUB2 integration for OSTree
perl-File-CheckTree.noarch : Run many file-test checks on a tree
perl-HTML-Tree.noarch : HTML tree handling modules for Perl
perl-Tree-DAG_Node.noarch : Class for representing nodes in a tree
perl-XML-TreeBuilder.noarch : Parser that builds a tree of XML::Element objects
subscription-manager-plugin-ostree.x86_64 : A plugin for handling OSTree
                                          : content.
texlive-pst-tree.noarch : Trees, using pstricks
texlive-pst-tree-doc.noarch : Documentation for pst-tree
tree.x86_64 : File system tree viewer
baobab.x86_64 : A graphical directory tree analyzer
cscope.x86_64 : C source code tree search and browse tool
drpmsync.x86_64 : Sync a file tree with deltarpms
dtc.x86_64 : Device Tree Compiler
gitk.noarch : Git revision tree visualiser
hardlink.x86_64 : Create a tree of hardlinks
libfdt.x86_64 : Device tree library
libfdt-devel.x86_64 : Development headers for device tree library
perl-Class-ISA.noarch : Report the search path for a class's ISA tree
perl-File-Path.noarch : Create or remove directory trees
perl-Test-ClassAPI.noarch : Provides basic first-pass API testing for large
                          : class trees
perl-XML-Twig.noarch : Perl module for processing huge XML documents in tree
                     : mode
perl-XML-XPathEngine.noarch : Re-usable XPath engine for DOM-like trees
python-lxml.x86_64 : ElementTree-like Python bindings for libxml2 and libxslt
python2-libfdt.x86_64 : Python 2 bindings for device tree library

  Name and summary matches only, use "search all" for everything.

目标包 tree.x86_64 : File system tree viewer 就在其中。对 bzip2 的搜索则是典型的「多包族」结果:

$ yum search bzip2
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
============================== N/S matched: bzip2 ==============================
bzip2-devel.i686 : Libraries and header files for apps which will use bzip2
bzip2-devel.x86_64 : Libraries and header files for apps which will use bzip2
bzip2-libs.i686 : Libraries for applications using bzip2
bzip2-libs.x86_64 : Libraries for applications using bzip2
perl-Compress-Raw-Bzip2.x86_64 : Low-level interface to bzip2 compression
                               : library
bzip2.x86_64 : A file compression utility

  Name and summary matches only, use "search all" for everything.

💡 要点:默认只搜名称与摘要(表头 N/S matched),尾行提示加 search all 可扩展到描述全文;多关键词是「与」关系(都要命中才列出);i686/x86_64 双架构并列时按需选择,64 位系统一般取 x86_64。想要「文件 → 包」的反查用 3.9 的 provides 而不是 search。

3.7 info:包详情(未安装/已安装两种形态)

info 显示包的元数据详情。未安装时归入 Available Packages 分节,Repo 字段直接给源名:

$ yum info tree
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Available Packages
Name        : tree
Arch        : x86_64
Version     : 1.6.0
Release     : 10.el7
Size        : 46 k
Repo        : base
Summary     : File system tree viewer
URL         : http://mama.indstate.edu/users/ice/tree/
License     : GPLv2+
Description : The tree utility recursively displays the contents of directories
            : in a tree-like format.  Tree is basically a UNIX port of the DOS
            : tree utility.

安装后再查同一包,变为 Installed Packages 分节,并多出 From repo 字段记录「从哪个源装的」:

$ yum info tree
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Installed Packages
Name        : tree
Arch        : x86_64
Version     : 1.6.0
Release     : 10.el7
Size        : 87 k
Repo        : installed
From repo   : base
Summary     : File system tree viewer
URL         : http://mama.indstate.edu/users/ice/tree/
License     : GPLv2+
Description : The tree utility recursively displays the contents of directories
            : in a tree-like format.  Tree is basically a UNIX port of the DOS
            : tree utility.

💡 要点:Size 在两种形态下含义不同——Available 时是下载包体积(46 k),Installed 时是安装后占用(87 k);Repo : installed + From repo : base 组合是排查「这包当初从哪来的」的最快途径;info 不带包名时列出全部包的信息(量大,慎用),配合 yum info installed/yum info available 可按状态过滤。

3.8 list:四种清单(installed/available/updates/recent)

list 按状态列出「包名.架构 版本 源」三列清单,四种常用形态逐一实测。

按包名查询(未安装时显示可用条目):

$ yum list tree
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Available Packages
tree.x86_64                          1.6.0-10.el7                           base

list installed:已安装清单(本机 yum list installed | wc -l 实测 150 行,含表头),头部节选:

$ yum list installed | head -6
Loaded plugins: fastestmirror, ovl
Installed Packages
acl.x86_64                                2.2.51-15.el7                 @CentOS
audit-libs.x86_64                         2.8.5-4.el7                   @CentOS
basesystem.noarch                         10.0-7.el7.centos             @CentOS
bash.x86_64                               4.2.46-34.el7                 @CentOS


Exiting on Broken Pipe

list available:可用清单(实测 wc -l 10382 行),头部节选:

$ yum list available | head -6
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Available Packages
389-ds-base.x86_64                        1.3.11.1-5.el7_9               updates
389-ds-base-devel.x86_64                  1.3.11.1-5.el7_9               updates
389-ds-base-libs.x86_64                   1.3.11.1-5.el7_9               updates


Exiting on Broken Pipe

list updates:可升级清单(实测 54 行),头部节选:

$ yum list updates | head -8
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Updated Packages
bash.x86_64                        4.2.46-35.el7_9                       updates
bind-license.noarch                32:9.11.4-26.P2.el7_9.16              updates
binutils.x86_64                    2.27-44.base.el7_9.1                  updates
ca-certificates.noarch             2023.2.60_v7.0.306-72.el7_9           updates
centos-release.x86_64              7-9.2009.2.el7.centos                 updates

list recent:最近 7 天(/etc/yum.conf 的 recent 值)新加入源的包。归档源已冻结,实测为空(只有表头,退出码 0):

$ yum list recent
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile

💡 要点:第三列的 @ 前缀(@CentOS、@base、@epel)表示已安装且标明安装来源,无 @ 则是可用状态;Exiting on Broken Pipe 不是错误——yum list ... | head 时 head 读完提前退出、yum 继续写 stdout 收到 SIGPIPE 而中断,属正常现象(详见 5.x FAQ Q5);yum list 'bash*' 支持通配,批量排查包名很好用。

3.9 provides / whatprovides:反查文件归属

provides(whatprovides 是其别名)回答「某个文件/能力由哪个包提供」,支持任意路径与通配。反查 /etc/centos-release 归谁(结果覆盖 base/updates 里的三个历史版本与已装条目):

$ yum provides /etc/centos-release
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
centos-release-7-9.2009.0.el7.centos.x86_64 : CentOS Linux release file
Repo        : base
Matched from:
Filename    : /etc/centos-release




centos-release-7-9.2009.1.el7.centos.x86_64 : CentOS Linux release file
Repo        : updates
Matched from:
Filename    : /etc/centos-release




centos-release-7-9.2009.2.el7.centos.x86_64 : CentOS Linux release file
Repo        : updates
Matched from:
Filename    : /etc/centos-release




centos-release-7-9.2009.0.el7.centos.x86_64 : CentOS Linux release file
Repo        : @CentOS
Matched from:
Filename    : /etc/centos-release

用通配反查 iostat 命令归属(输出节选,最终命中 sysstat):

$ yum whatprovides '*/iostat'
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
pcp-4.3.2-12.el7.x86_64 : System-level performance monitoring and performance
                        : management
Repo        : base
Matched from:
Filename    : /var/lib/pcp/config/pmlogconf/tools/iostat

sysstat-10.1.5-19.el7.x86_64 : Collection of performance monitoring tools for
                             : Linux
Repo        : base
Matched from:
Filename    : /usr/bin/iostat

sysstat-10.1.5-20.el7_9.x86_64 : Collection of performance monitoring tools for
                               : Linux
Repo        : updates
Matched from:
Filename    : /usr/bin/iostat
(输出节选:实测首尾)

💡 要点:绝对路径必须写全(/usr/bin/iostat)或用 */iostat 这类通配,只写 iostat 会按「提供能力名」匹配而查不到;Repo : @CentOS 表示这个匹配来自已安装的包(装机时从安装介质装入);provides 也能查能力名(如 yum provides 'perl(Getopt::Long)' 反查 perl 模块归属),是解决「报错缺 so/缺模块该装哪个包」的万能钥匙。

3.10 repolist:软件源清单(all / -v / 临时启用禁用)

repolist 列出启用的软件源与各自的包数:

$ yum repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id          repo name                                                status
base             CentOS-7.9.2009 - Base                                   10072
epel             Extra Packages for Enterprise Linux 7 - x86_64           13791
extras           CentOS-7.9.2009 - Extras                                   526
updates          CentOS-7.9.2009 - Updates                                 6173
repolist: 30562

repolist all 额外显示被禁用的源(status 列变为 enabled: N / disabled 样式):

$ yum repolist all
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id                       repo name                           status
base                          CentOS-7.9.2009 - Base              enabled: 10072
epel                          Extra Packages for Enterprise Linux enabled: 13791
epel-debuginfo                Extra Packages for Enterprise Linux disabled
epel-source                   Extra Packages for Enterprise Linux disabled
epel-testing/x86_64           Extra Packages for Enterprise Linux disabled
epel-testing-debuginfo/x86_64 Extra Packages for Enterprise Linux disabled
epel-testing-source/x86_64    Extra Packages for Enterprise Linux disabled
extras                        CentOS-7.9.2009 - Extras            enabled:   526
updates                       CentOS-7.9.2009 - Updates           enabled:  6173
repolist: 30562

-v 详细模式暴露每个源的 baseurl、元数据更新时间与 repo 文件路径(排查「这个包到底从哪个 URL 来的」就靠它),节选:

$ yum -v repolist
Loading "fastestmirror" plugin
Loading "ovl" plugin
Config time: 0.004
rpmdb time: 0.001
ovl: Copying up (0) files from OverlayFS lower layer
Yum version: 3.4.3
Loading mirror speeds from cached hostfile
Setting up Package Sacks
pkgsack time: 0.005
Repo-id      : base
Repo-name    : CentOS-7.9.2009 - Base
Repo-revision: 1604001756
Repo-updated : Thu Oct 29 20:03:00 2020
Repo-pkgs    : 10072
Repo-size    : 8.9 G
Repo-baseurl : http://mirrors.aliyun.com/centos-vault/7.9.2009/os/x86_64/
Repo-expire  : 21600 second(s) (last: Fri Oct 16 16:29:46 2026)
  Filter     : read-only:present
Repo-filename: /etc/yum.repos.d/CentOS-Base.repo

Repo-id      : epel
Repo-name    : Extra Packages for Enterprise Linux 7 - x86_64
Repo-revision: 1719793483
Repo-updated : Mon Jul  1 00:25:02 2024
(输出节选:实测首尾)

配合 --disablerepo/--enablerepo 可以在单次命令里临时增删源(不落盘、不改 repo 文件),实测三种组合:

$ yum --disablerepo=base repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id          repo name                                                status
epel             Extra Packages for Enterprise Linux 7 - x86_64           13791
extras           CentOS-7.9.2009 - Extras                                   526
updates          CentOS-7.9.2009 - Updates                                 6173
repolist: 20490

$ yum --disablerepo=base --disablerepo=updates repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id          repo name                                                status
epel             Extra Packages for Enterprise Linux 7 - x86_64           13791
extras           CentOS-7.9.2009 - Extras                                   526
repolist: 14317

$ yum --disablerepo='*' --enablerepo=updates repolist
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
repo id                     repo name                                     status
updates                     CentOS-7.9.2009 - Updates                     6173
repolist: 6173

💡 要点:--disablerepo/--enablerepo 支持 shell 通配('*'、'epel-*',注意引号防 shell 展开),经典组合是 --disablerepo='*' --enablerepo=更新源名 实现只从指定源拉包;Repo-expire 21600 即元数据 6 小时过期,过期后 yum 自动重新拉取元数据(这就是 makecache 的定时版);-v 模式里 Repo-size : 8.9 G 能预估全量归档的磁盘需求。

3.11 makecache 与 clean:缓存构建与清理

makecache 预先把各源的元数据下载到本地(yum makecache fast 中的 fast 只构建最快站点缓存,yum 3.4.3 中两者都会输出 Metadata Cache Created):

$ yum makecache
Loaded plugins: fastestmirror, ovl
Determining fastest mirrors
Metadata Cache Created

$ yum makecache fast
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Metadata Cache Created

缓存落点是 /var/cache/yum/$basearch/$releasever/,四源元数据 + 包缓存实测占用 654M。clean 家族分级清理,全部实测(清理前后 du -sh 对比):

$ du -sh /var/cache/yum
654M	/var/cache/yum

$ yum clean packages
Loaded plugins: fastestmirror, ovl
Cleaning repos: base epel extras updates
1 package file removed

$ yum clean headers
Loaded plugins: fastestmirror, ovl
Cleaning repos: base epel extras updates
0 header files removed

$ yum clean metadata
Loaded plugins: fastestmirror, ovl
Cleaning repos: base epel extras updates
15 metadata files removed
24 sqlite files removed
0 metadata files removed

$ yum clean dbcache
Loaded plugins: fastestmirror, ovl
Cleaning repos: base epel extras updates
0 sqlite files removed

$ yum clean all
Loaded plugins: fastestmirror, ovl
Cleaning repos: base epel extras updates
Cleaning up list of fastest mirrors

$ du -sh /var/cache/yum
64K	/var/cache/yum

💡 要点:clean all = packages + metadata + dbcache + plugins 的合集(等于一次清空),清完 654M → 64K,是磁盘告警时的安全减肥项(代价是下一次任何 yum 命令都要重新拉元数据,~几十秒);clean packages 只删下载的 rpm 包文件(keepcache=1 时保留的包也在此列);改完 repo 配置的标准动作是 yum clean all && yum makecache。

3.12 history:事务历史与 undo / redo

yum 把每次成功(或交互中止)的装卸升级记为一笔带自增 ID 的事务,这是 yum 最像「数据库」的能力。history list 展示全量(本文实测至今共 14 笔,ID 1-2 是装机时刻的原始事务):

$ yum history list
Loaded plugins: fastestmirror, ovl
ID     | Login user               | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
    14 | System <unset>           | 2026-10-16 16:34 | Install        |    1
    13 | System <unset>           | 2026-10-16 16:34 | Erase          |    1
    12 | System <unset>           | 2026-10-16 16:32 | Erase          |   12 EE
    11 | System <unset>           | 2026-10-16 16:32 | Erase          |    1
    10 | System <unset>           | 2026-10-16 16:32 | Install        |   33 EE
     9 | System <unset>           | 2026-10-16 16:32 | Erase          |    1
     8 | System <unset>           | 2026-10-16 16:32 | Update         |    1
     7 | System <unset>           | 2026-10-16 16:32 | Downgrade      |    1
     6 | System <unset>           | 2026-10-16 16:32 | Update         |    1
     5 | System <unset>           | 2026-10-16 16:32 | Install        |    1
     4 | System <unset>           | 2026-10-16 16:27 | Install        |    1
     3 | System <unset>           | 2026-10-16 16:27 | Install        |    1
     2 | root <root>              | 2020-11-13 01:55 | Erase          |   25 E<
     1 | root <root>              | 2020-11-13 01:53 | Install        |  174 >

history info <ID> 展示事务全细节(命令行、rpmdb 前后指纹、动了哪些包):

$ yum history info 5
Loaded plugins: fastestmirror, ovl
Transaction ID : 5
Begin time     : Fri Oct 16 16:32:09 2026
Begin rpmdb    : 150:326307172106fa10f6f5bd373ead56ff05b280d7
End time       :                           (0 seconds)
End rpmdb      : 151:f57ebb436fa433003148dff99d81f2e4e56a837e
User           : System <unset>
Return-Code    : Success
Command Line   : install -y sl
Transaction performed with:
    Installed     rpm-4.11.3-45.el7.x86_64                        @CentOS
    Installed     yum-3.4.3-168.el7.centos.noarch                 @CentOS
    Installed     yum-plugin-fastestmirror-1.1.31-54.el7_8.noarch @CentOS
Packages Altered:
    Install sl-5.02-1.el7.x86_64 @epel

history undo <ID> 反演该事务(装的删掉、删的装回、升级的退回),实测撤销 5 号「install sl」:

$ yum -y history undo 5
Loaded plugins: fastestmirror, ovl
Undoing transaction 5, from Fri Oct 16 16:32:09 2026
    Install sl-5.02-1.el7.x86_64 @epel
Resolving Dependencies
--> Running transaction check
---> Package sl.x86_64 0:5.02-1.el7 will be erased
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package       Arch              Version                 Repository        Size
================================================================================
Removing:
 sl            x86_64            5.02-1.el7              @epel             17 k

Transaction Summary
================================================================================
Remove  1 Package

Installed size: 17 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Erasing    : sl-5.02-1.el7.x86_64                                         1/1
  Verifying  : sl-5.02-1.el7.x86_64                                         1/1

Removed:
  sl.x86_64 0:5.02-1.el7

Complete!
$ rpm -q sl
package sl is not installed

history redo <ID> 原样重放事务,实测重放 5 号把 sl 装回:

$ yum -y history redo 5
Loaded plugins: fastestmirror, ovl
Repeating transaction 5, from Fri Oct 16 16:32:09 2026
    Install sl-5.02-1.el7.x86_64 @epel
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package sl.x86_64 0:5.02-1.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package       Arch              Version                  Repository       Size
================================================================================
Installing:
 sl            x86_64            5.02-1.el7               epel             14 k

Transaction Summary
================================================================================
Install  1 Package

Total download size: 14 k
Installed size: 17 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : sl-5.02-1.el7.x86_64                                         1/1
  Verifying  : sl-5.02-1.el7.x86_64                                         1/1

Installed:
  sl.x86_64 0:5.02-1.el7

Complete!
$ rpm -q sl
sl-5.02-1.el7.x86_64

undo/redo 各自生成新事务(13 号 Erase、14 号 Install),重放后的事务详情结构与原事务一致(Command Line : -y history redo 5):

$ yum history info 14
Loaded plugins: fastestmirror, ovl
Transaction ID : 14
Begin time     : Fri Oct 16 16:34:17 2026
Begin rpmdb    : 169:6e22c7fec58ab2e7b4435eaa0e53d9daa255bbef
End time       :                           (0 seconds)
End rpmdb      : 170:fdcfec53382e34feedbddc70fed1125afba4696a
User           : System <unset>
Return-Code    : Success
Command Line   : -y history redo 5
Transaction performed with:
    Installed     rpm-4.11.3-45.el7.x86_64                        @CentOS
    Installed     yum-3.4.3-168.el7.centos.noarch                 @CentOS
    Installed     yum-plugin-fastestmirror-1.1.31-54.el7_8.noarch @CentOS
Packages Altered:
    Install sl-5.02-1.el7.x86_64 @epel

history summary 按操作人聚合统计:

$ yum history summary | head -12
Loaded plugins: fastestmirror, ovl
Login user                 | Time                | Action(s)        | Altered
-------------------------------------------------------------------------------
System <unset>             | Last day            | D, E, I, U       |       56
root <root>                | Over a year ago     | E, I             |      199

💡 要点:

  1. undo/redo 不是版本回滚指针,而是「生成一笔新事务」:ID 单调递增、历史不可改写,所以反复 undo/redo 同一事务是安全的幂等操作(前提是相关源仍能提供那些包——归档源恰好满足)。
  2. history list 最后一列 Altered 的数字是被改动包数,后缀字母是动作缩写(I=Install、U=Update、E=Erase、D=Downgrade),> / < 标记该事务里存在「超出当前软件源版本范围」的包(如装机初始事务来自安装介质,实测 ID 1 显示 174 >)。
  3. yum history 是事后审计利器:「这台机器上周装过什么、谁执行的、从哪个源」三问都能从 history info 一处拿到答案(User 与 Command Line 字段)。

3.13 autoremove:清理孤儿依赖(reason=dep 机制与风险)

yum 会为每个已安装包在 rpmdb 附加库(yumdb)里记录安装原因:user(用户显式安装)或 dep(作为依赖自动拉入)。卸载主包后,reason=dep 且不再被任何包依赖的就成为孤儿,autoremove 专门清理它们。先看一个真实依赖链:安装 vim-enhanced 拉入 33 个包(19 M),事务表节选:

$ yum install -y vim-enhanced
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package vim-enhanced.x86_64 2:7.4.629-8.el7_9 will be installed
--> Processing Dependency: vim-common = 2:7.4.629-8.el7_9 for package: 2:vim-enhanced-7.4.629-8.el7_9.x86_64
--> Processing Dependency: which for package: 2:vim-enhanced-7.4.629-8.el7_9.x86_64
--> Processing Dependency: perl(:MODULE_COMPAT_5.16.3) for package: 2:vim-enhanced-7.4.629-8.el7_9.x86_64
--> Processing Dependency: libperl.so()(64bit) for package: 2:vim-enhanced-7.4.629-8.el7_9.x86_64
--> Processing Dependency: libgpm.so.2()(64bit) for package: 2:vim-enhanced-7.4.629-8.el7_9.x86_64
...
Transaction Summary
================================================================================
Install  1 Package (+32 Dependent packages)

Total download size: 19 M
Installed size: 63 M
...
  Installing : 2:vim-enhanced-7.4.629-8.el7_9.x86_64                      33/33

Installed:
  vim-enhanced.x86_64 2:7.4.629-8.el7_9

Dependency Installed:
  gpm-libs.x86_64 0:1.20.7-6.el7
  groff-base.x86_64 0:1.22.2-8.el7
  perl.x86_64 4:5.16.3-299.el7_9
  ...(共 32 个依赖包,节选)
  vim-common.x86_64 2:7.4.629-8.el7_9
  vim-filesystem.x86_64 2:7.4.629-8.el7_9
  which.x86_64 0:2.20-7.el7

Complete!

卸载主包 vim-enhanced 后,依赖包 vim-common、gpm-libs、vim-filesystem、which 全部留在系统里,用 yumdb 查证它们的安装原因确为 dep:

$ yum remove -y vim-enhanced
Loaded plugins: fastestmirror, ovl
...
Removed:
  vim-enhanced.x86_64 2:7.4.629-8.el7_9

Complete!
$ rpm -q vim-common gpm-libs vim-filesystem
vim-common-7.4.629-8.el7_9.x86_64
gpm-libs-1.20.7-6.el7.x86_64
vim-filesystem-7.4.629-8.el7_9.x86_64

$ yumdb info vim-common | grep -E 'reason|from_repo'
     from_repo = updates
     reason = dep

yum autoremove 预演(不带 -y,回车前的完整清单,注意它连系统原有的 dep 标记包也一并圈了进来):

$ yum autoremove
Loaded plugins: fastestmirror, ovl
Resolving Dependencies
--> Running transaction check
---> Package bc.x86_64 0:1.06.95-13.el7 will be erased
---> Package bind-license.noarch 32:9.11.4-26.P2.el7 will be erased
---> Package dbus-python.x86_64 0:1.1.1-9.el7 will be erased
---> Package geoipupdate.x86_64 0:2.5.0-2.el7 will be erased
---> Package gpm-libs.x86_64 0:1.20.7-6.el7 will be erased
---> Package hostname.x86_64 0:3.13-3.el7_7.1 will be erased
---> Package python-gobject-base.x86_64 0:3.22.0-1.el7_4.1 will be erased
---> Package vim-common.x86_64 2:7.4.629-8.el7_9 will be erased
---> Package which.x86_64 0:2.20-7.el7 will be erased
--> Finished Dependency Resolution
--> Finding unneeded leftover dependencies
---> Marking dbus-glib to be removed - no longer needed by dbus-python
---> Marking gobject-introspection to be removed - no longer needed by python-gobject-base
---> Marking vim-filesystem to be removed - no longer needed by vim-common
Found and removing 3 unneeded dependencies
...
Transaction Summary
================================================================================
Remove  9 Packages (+3 Dependent packages)

Installed size: 25 M
Is this ok [y/N]: Exiting on user command
Your transaction was saved, rerun it with:
 yum load-transaction /tmp/yum_save_tx.2026-10-16.16-32.J4ZHsX.yumtx

确认 -y 执行后全部清掉并复核:

$ yum autoremove -y
Loaded plugins: fastestmirror, ovl
...
  Erasing    : 2:vim-common-7.4.629-8.el7_9.x86_64                         1/12
  ...
Removed:
  bc.x86_64 0:1.06.95-13.el7
  bind-license.noarch 32:9.11.4-26.P2.el7
  dbus-python.x86_64 0:1.1.1-9.el7
  geoipupdate.x86_64 0:2.5.0-2.el7
  gpm-libs.x86_64 0:1.20.7-6.el7
  hostname.x86_64 0:3.13-3.el7_7.1
  python-gobject-base.x86_64 0:3.22.0-1.el7_4.1
  vim-common.x86_64 2:7.4.629-8.el7_9
  which.x86_64 0:2.20-7.el7

Dependency Removed:
  dbus-glib.x86_64 0:0.100-7.el7
  gobject-introspection.x86_64 0:1.56.1-1.el7
  vim-filesystem.x86_64 2:7.4.629-8.el7_9

Complete!
$ rpm -q vim-common gpm-libs vim-filesystem
package vim-common is not installed
package gpm-libs is not installed
package vim-filesystem is not installed

💡 要点:

  1. CentOS 7.9 的 yum 3.4.3-168 上 autoremove 是内置命令——实测在未安装 yum-plugin-autoremove(rpm -q 确认未装、源中也不存在该包)的情况下直接可用;更早的 7.x 小版本才需要先装该插件。
  2. 预览清单就是唯一的安全带:本例中它连 hostname、bc、bind-license、which、dbus-python 这类基础包都圈了进去——它们的安装原因在装机阶段就被标成 dep。执行前逐行读清单,不想要的包先 yumdb set reason user 包名 把原因改成 user,autoremove 就会放过它。
  3. 不带 -y 交互处直接回车/中断,事务不执行、退出码 1,并提示可用 yum load-transaction /tmp/yum_save_tx.*.yumtx 重放(3.12 的 load-transaction 子命令即用于此)。

3.14 --showduplicates:同包多版本可见性

repo 元数据默认只暴露每个包的最新版本,加 --showduplicates 后同包在不同源/不同历史版本的全部条目都列出。base(GA 版)与 updates(更新版)双版本并存的 bash:

$ yum --showduplicates list bash
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Installed Packages
bash.x86_64                       4.2.46-34.el7                          @CentOS
Available Packages
bash.x86_64                       4.2.46-34.el7                          base
bash.x86_64                       4.2.46-35.el7_9                        updates

💡 要点:--showduplicates 只改变可见性,不改变 update/install 的默认选版行为(仍取最高版本);要指定版本安装用 NEVRA 全名:yum install bash-4.2.46-34.el7(版本号可省 arch);配合归档源使用时它是确认「旧版本还在不在」的第一工具(3.4 downgrade 的前置检查)。

3.15 --downloadonly:只下载不安装

--downloadonly 把解析好的包下载到指定目录后退出,用于离线分发或本地安装。zsh(2.4M)实测:

$ mkdir -p /root/dl
$ yum install -y --downloadonly --downloaddir=/root/dl zsh
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package zsh.x86_64 0:5.0.2-34.el7_8.2 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package       Arch             Version                    Repository      Size
================================================================================
Installing:
 zsh           x86_64           5.0.2-34.el7_8.2           base           2.4 M

Transaction Summary
================================================================================
Install  1 Package

Total download size: 2.4 M
Installed size: 5.6 M
Background downloading packages, then exiting:
exiting because "Download Only" specified
$ ls -lh /root/dl/
total 2.4M
-rw-r--r-- 1 root root 2.4M Apr  8  2020 zsh-5.0.2-34.el7_8.2.x86_64.rpm

下载下来的 rpm 可以直接交给 yum 本地安装(Repository 列显示为本地路径):

$ yum install -y /root/dl/zsh-5.0.2-34.el7_8.2.x86_64.rpm
Loaded plugins: fastestmirror, ovl
Examining /root/dl/zsh-5.0.2-34.el7_8.2.x86_64.rpm: zsh-5.0.2-34.el7_8.2.x86_64
Marking /root/dl/zsh-5.0.2-34.el7_8.2.x86_64.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package zsh.x86_64 0:5.0.2-34.el7_8.2 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package Arch       Version              Repository                        Size
================================================================================
Installing:
 zsh     x86_64     5.0.2-34.el7_8.2     /zsh-5.0.2-34.el7_8.2.x86_64     5.6 M

Transaction Summary
================================================================================
Install  1 Package

Total size: 5.6 M
Installed size: 5.6 M
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : zsh-5.0.2-34.el7_8.2.x86_64                                  1/1
  Verifying  : zsh-5.0.2-34.el7_8.2.x86_64                                  1/1

Installed:
  zsh.x86_64 0:5.0.2-34.el7_8.2

Complete!

配套的另一个参数是 --setopt=keepcache=1:正常安装后 yum 会删除下载的 rpm,keepcache=1 把它们留在 /var/cache/yum/.../packages/ 里,效果与 --downloadonly 类似但走完整安装流程:

$ yum --setopt=keepcache=1 install -y tree
Loaded plugins: fastestmirror, ovl
...
  Installing : tree-1.6.0-10.el7.x86_64                                     1/1

Installed:
  tree.x86_64 0:1.6.0-10.el7

Complete!
$ ls -lh /var/cache/yum/x86_64/7/base/packages/
total 52K
-rw-r--r-- 1 root root 47K Jul  4  2014 tree-1.6.0-10.el7.x86_64.rpm

💡 要点:--downloadonly 在 yum 3.4.3-168 是内置能力(无需 yum-plugin-downloadonly,早期版本需要);对目标机与联网机版本一致的场景,先 --downloadonly --downloaddir 攒包再离线安装是标准内网交付流;本地 rpm 安装时 yum 仍会联网补齐缺失依赖,纯离线需求用 rpm -ivh 或把依赖一并 downloadonly。

3.16 --installroot:安装到独立根目录

--installroot 把 rpmdb、缓存、安装动作整体切到指定目录,目标目录里生成一套独立的包数据库,宿主 rpmdb 不受影响——救援环境、构建精简根文件系统的标准工具。用无依赖链的 epel-release 演示:

$ yum --installroot=/root/testroot --releasever=7 install -y epel-release
Loaded plugins: fastestmirror, ovl
Determining fastest mirrors
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-14 will be installed
--> Processing Dependency: redhat-release >= 7 for package: epel-release-7-14.noarch
--> Running transaction check
---> Package centos-release.x86_64 0:7-9.2009.2.el7.centos will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package             Arch        Version                     Repository    Size
================================================================================
Installing:
 epel-release        noarch      7-14                        epel          15 k
Installing for dependencies:
 centos-release      x86_64      7-9.2009.2.el7.centos       updates       27 k

Transaction Summary
================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 42 k
Installed size: 70 k
Downloading packages:
warning: /root/testroot/var/cache/yum/x86_64/7/updates/packages/centos-release-7-9.2009.2.el7.centos.x86_64.rpm: Header V4 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Public key for centos-release-7-9.2009.2.el7.centos.x86_64.rpm is not installed
warning: /root/testroot/var/cache/yum/x86_64/7/epel/packages/epel-release-7-14.noarch.rpm: Header V4 RSA/SHA256 Signature, key ID 352c64e5: NOKEY
Public key for epel-release-7-14.noarch.rpm is not installed
--------------------------------------------------------------------------------
Total                                              298 kB/s |  42 kB  00:00
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
Importing GPG key 0x352C64E5:
 Userid     : "Fedora EPEL (7) <epel@fedoraproject.org>"
 Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>"
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : centos-release-7-9.2009.2.el7.centos.x86_64                  1/2
  Installing : epel-release-7-14.noarch                                     2/2
  Verifying  : epel-release-7-14.noarch                                     1/2
  Verifying  : centos-release-7-9.2009.2.el7.centos.x86_64                  2/2

Installed:
  epel-release.noarch 0:7-14

Dependency Installed:
  centos-release.x86_64 7-9.2009.2.el7.centos

Complete!

验证独立根内的产物与宿主不受影响,然后清理:

$ ls -l /root/testroot/etc/yum.repos.d/
total 48
-rw-r--r-- 1 root root 1664 May 21  2024 CentOS-Base.repo
-rw-r--r-- 1 root root 1309 May 21  2024 CentOS-CR.repo
-rw-r--r-- 1 root root  649 May 21  2024 CentOS-Debuginfo.repo
-rw-r--r-- 1 root root  630 May 21  2024 CentOS-Media.repo
-rw-r--r-- 1 root root 1331 May 21  2024 CentOS-Sources.repo
-rw-r--r-- 1 root root 9454 May 21  2024 CentOS-Vault.repo
-rw-r--r-- 1 root root  314 May 21  2024 CentOS-fasttrack.repo
-rw-r--r-- 1 root root  616 May 21  2024 CentOS-x86_64-kernel.repo
-rw-r--r-- 1 root root 1457 Sep  4  2021 epel-testing.repo
-rw-r--r-- 1 root root 1358 Sep  4  2021 epel.repo

$ rpm -q epel-release
epel-release-7-11.noarch        ← 宿主 rpmdb 未受影响(测试根里装的是 7-14)

$ ls /root/testroot/var/lib/rpm/ | head -8
Basenames
Conflictname
Dirnames
Group
Installtid
Name
Obsoletename
Packages

$ rm -rf /root/testroot

💡 要点:--releasever=7 必须显式给——installroot 里没有 centos-release 包时 yum 解析不出 $releasever,会报 Error: Need to pass a list of pkgs to install 类错误;宿主的 repo 配置会被 installroot 沿用(除非 installroot 里已有自己的 /etc/yum.repos.d/),GPG 密钥仍取宿主的 /etc/pki/rpm-gpg/;普通包(如 tree 依赖 glibc)在空 installroot 里安装时会连依赖链一起拉进去,体积远超包本身,本例特意选 epel-release 就是为了展示「最小依赖」形态。

3.17 -q / -v / --noplugins:输出控制三件套

-q(quiet)压制插件加载提示与下载进度条,只保留结果本体,适合管道取值;-v(verbose)反过来暴露配置加载、插件、耗时等细节;--noplugins 完全跳过插件。三者对同一查询的输出头部差异实测:

$ yum info sl
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Installed Packages
Name        : sl
...

$ yum -q info sl
Installed Packages
Name        : sl
...

$ yum --noplugins repolist | head -3
repo id          repo name                                                status

-v 模式下能看到插件装载、配置耗时等诊断信息(3.10 已展示其 repolist 形态)。sl 的完整 info 输出顺带展示 From repo 的另一种取值(epel):

$ yum -q info sl
Installed Packages
Name        : sl
Arch        : x86_64
Version     : 5.02
Release     : 1.el7
Size        : 17 k
Repo        : installed
From repo   : epel
Summary     : Joke command for when you type 'sl' instead of 'ls'
URL         : https://github.com/mtoyoda/sl
License     : Copyright only
Description : The sl (Steam Locomotive) command is a joke which displays a train
            : on your terminal when you accidentally type 'sl' instead of 'ls'.

💡 要点:脚本里取值永远配 -q(如 yum -q list installed | wc -l),否则 Loaded plugins 表头会混进结果;--noplugins 排障时用来二分「是 yum 本体的问题还是插件的问题」;-q/-v/-d 0~10/-e 0~10 四者的关系:-q/-v 是 debuglevel/errorlevel 的便捷封装,深度排障用 -d 3 -e 1 这类细粒度组合。

3.18 group:包组管理(list / info / install / remove / mark convert)

group(groups 同义)管理「包组」——一组预定义软件集合(如 Development Tools)。group list 分三段展示(未初始化组文件时先给一行提示,属正常现象):

$ yum group list
Loaded plugins: fastestmirror, ovl
There is no installed groups file.
Maybe run: yum groups mark convert (see man yum)
Determining fastest mirrors
Available Environment Groups:
   Minimal Install
   Compute Node
   Infrastructure Server
   File and Print Server
   Cinnamon Desktop
   MATE Desktop
   Basic Web Server
   Virtualization Host
   Server with GUI
   GNOME Desktop
   KDE Plasma Workspaces
   Development and Creative Workstation
Available Groups:
   Cinnamon
   Compatibility Libraries
   Console Internet Tools
   Development Tools
   Educational Software
   Electronic Lab
   Fedora Packager
   General Purpose Desktop
   Graphical Administration Tools
   Haskell
   LXQt Desktop
   Legacy UNIX Compatibility
   MATE
   Milkymist
   Scientific Support
   Security Tools
   Smart Card Support
   System Administration Tools
   System Management
   TurboGears application framework
   Xfce
Done

group info 查看组的包构成,包分 mandatory(必装)/default(默认装)/optional(可选装)三档,行首 + 表示当前未安装。Development Tools(节选):

$ yum group info "Development Tools"
There is no installed groups file.
Maybe run: yum groups mark convert (see man yum)
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile

Group: Development Tools
 Group-Id: development
 Description: A basic development environment.
 Mandatory Packages:
   +autoconf
   +automake
    binutils
   +bison
   +flex
   +gcc
   +gcc-c++
   +gettext
   +libtool
   +make
   +patch
    pkgconfig
   +redhat-rpm-config
   +rpm-build
   +rpm-sign
 Default Packages:
   +byacc
   +cscope
   +ctags
   +diffstat
   +doxygen
   +elfutils
   +gcc-gfortran
   +git
   +indent
   +intltool
   +patchutils
   +rcs
   +subversion
   +swig
   +systemtap
 Optional Packages:
   ElectricFence
   ant
   babel
   bzr
   ccache
   ...

group install 默认只装 mandatory + default 两档。选一个轻量组 System Administration Tools(仅 default 包 lsscsi)实测:

$ yum -y group install "System Administration Tools"
Loaded plugins: fastestmirror, ovl
There is no installed groups file.
Maybe run: yum groups mark convert (see man yum)
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package lsscsi.x86_64 0:0.27-6.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package          Arch             Version                 Repository      Size
================================================================================
Installing for group install "System Administration Tools":
 lsscsi           x86_64           0.27-6.el7              base            47 k

Transaction Summary
================================================================================
Install  1 Package

Total download size: 47 k
Installed size: 88 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : lsscsi-0.27-6.el7.x86_64                                     1/1
  Verifying  : lsscsi-0.27-6.el7.x86_64                                     1/1

Installed:
  lsscsi.x86_64 0:0.27-6.el7

Complete!

group remove 卸载组内由该组装入的包:

$ yum -y group remove "System Administration Tools"
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
No environment named System Administration Tools exists
Resolving Dependencies
--> Running transaction check
---> Package lsscsi.x86_64 0:0.27-6.el7 will be erased
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package          Arch             Version                Repository       Size
================================================================================
Removing:
 lsscsi           x86_64           0.27-6.el7             @base            88 k

Transaction Summary
================================================================================
Remove  1 Package
...
Removed:
  lsscsi.x86_64 0:0.27-6.el7

Complete!

groups mark convert 把旧式组记录转换为新式组标记文件,消除开头那行 There is no installed groups file 提示:

$ yum groups mark convert
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Converted old style groups to objects.

转换后 group list 的 Installed Groups: 段开始出现内容(组标记持久保存在 /var/lib/yum/groups/installed,与包是否还在是两回事):

$ yum group list | head -16
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Available Environment Groups:
   Minimal Install
   Compute Node
   Infrastructure Server
   File and Print Server
   Cinnamon Desktop
   MATE Desktop
   Basic Web Server
   Virtualization Host
   Server with GUI
   GNOME Desktop
   KDE Plasma Workspaces
   Development and Creative Workstation
Installed Groups:
   System Administration Tools
Available Groups:
   Cinnamon

💡 要点:group install "Development Tools" 在最小安装机上会装入 gcc/make/git 等 40+ 包(约 200 MB 级),CI 环境按需改用 --setopt=group_package_types=mandatory 只装必装档;group remove 输出里的 No environment named ... exists 只是「这不是环境组、是普通组」的提示,卸载照常执行;要只装 optional 里的个别包,直接 yum install 包名,不必整组拉入。

3.19 其他子命令速览(deplist / check 实测 + 低频命令表)

deplist 列出包的能力依赖及其候选提供者:

$ yum deplist tree | head -20
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
package: tree.x86_64 1.6.0-10.el7
  dependency: libc.so.6(GLIBC_2.14)(64bit)
   provider: glibc.x86_64 2.17-326.el7_9.3
  dependency: rtld(GNU_HASH)
   provider: glibc.x86_64 2.17-326.el7_9.3
   provider: glibc.i686 2.17-326.el7_9.3

check 体检 rpmdb 一致性(无问题时输出一行 check all 并返回 0):

$ yum check
Loaded plugins: fastestmirror, ovl
check all
$ echo $?
0

其余低频子命令依赖特定场景,按 --help 原文与手册语义速览:

子命令语义(摘自 --help 实测原文)典型场景
reinstallreinstall a package怀疑二进制损坏/丢文件时重装同版本
swapSimple way to swap packages一条事务里「卸 A 装 B」,如 swap remove vim-minimal install vim-enhanced
shellRun an interactive yum shell交互式连续操作,共享一次依赖解析
load-transactionload a saved transaction from filename重放 /tmp/yum_save_tx.*.yumtx 保存的事务
versionDisplay a version for the machine and/or available repos按 group/维度统计已装与可升级
update-minimalWorks like upgrade, but goes to the 'newest' package match which fixes a problem只打最小安全修复集
distribution-synchronizationSynchronize installed packages to the latest available versions对齐到源内最新(含降级到源版本)
fs / fssnapshotfilesystem 数据清理 / 快照管理最小化系统里删文档、语言包腾空间
repo-pkgsTreat a repo. as a group of packages按「整源」批量 install/remove(如临时源清理)
updateinfoActs on repository update information查看安全公告/errata 元数据
-C, --cacheonlyrun entirely from system cache断网时用已有缓存执行查询/安装

💡 说明:上表除 reinstall/swap 依赖演示包状态、shell 为交互模式外,deplist 与 check 已在上方实测;其余命令语义以 --help 原文为准,本文未逐一展开实测。

3.20 包管理器对照拓展表

Linux 主流包管理器的常用操作对照(本文主角 yum 为 RHEL/CentOS 7 系的基准,RHEL 8+/Fedora 已切换到 dnf,命令面几乎兼容 yum):

包管理器发行版安装卸载更新源索引升级搜索包详情清理缓存
yum 3.4.3RHEL/CentOS 7installremovemakecacheupdate/upgradesearchinfoclean all
dnfRHEL 8+、Fedorainstallremove(autoremove)makecacheupgradesearchinfoclean all
aptDebian/Ubuntuinstallremove/purgeupdateupgradesearchshowclean
pacmanArch-S-R/-Rs-Sy-Syu-Ss-Si-Sc
zypperopenSUSEinstallremoverefreshupdatesearchinfoclean
apkAlpineadddelupdateupgradesearchinfocache clean
emergeGentooemerge <pkg>emerge -c--sync-uDN @world-s--info <pkg>eclean-dist
xbpsVoidxbps-install <pkg>xbps-remove <pkg>-S-Suxbps-query -Rsxbps-query -Rxbps-remove -O

关键差异解读:yum/apt/dnf 是「先更新索引、后安装」两步分离型(apt update + install,yum 3.x 则在每条命令里自动按需刷新元数据);pacman/zypper/apk 把索引更新并入 -Syu/refresh/update 等单一动作;孤儿依赖清理上,apt 的 autoremove、dnf 的 autoremove、pacman 的 -Rs、xbps 的 xbps-remove -O 与本文 yum 的 autoremove 同源同义,而 apk/emerge 需要各自的世界维护命令(apk fix、emerge --depclean)。

💡 技术拓展:包依赖解析器也经历了代际更替——yum 用自研的 depsolver(SAT 时代前的启发式),dnf 换成了 libsolv(SAT 求解器),apt 系用 APT 的 resolver + dpkg,Alpine apk 用轻量 SAT。同一条依赖链,yum 与 dnf 可能给出不同但都合法的解决方案,迁移 CentOS 7 → RHEL 8 时依赖相关的行为差异大多源于此。

四、实战示例

4.1 场景一:EOL 环境软件源从故障到可用的一键序列

接手任意一台 CentOS 7 机器,先跑这套「备份 → 写归档 repo → 重建缓存 → 验证」序列(方案 A 的可复制版,命令与 2.4.3 相同,此处按执行顺序整合):

mkdir -p /etc/yum.repos.d/backup
mv /etc/yum.repos.d/CentOS-*.repo /etc/yum.repos.d/backup/
cat > /etc/yum.repos.d/CentOS-Base.repo <<'EOF'
# CentOS-7.9.2009 阿里云归档软件源(CentOS 7 EOL 后官方源已下线,改用归档)
[base]
name=CentOS-7.9.2009 - Base
baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/os/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[updates]
name=CentOS-7.9.2009 - Updates
baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/updates/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[extras]
name=CentOS-7.9.2009 - Extras
baseurl=http://mirrors.aliyun.com/centos-vault/7.9.2009/extras/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1
EOF
yum clean all && yum makecache && yum repolist

最终验证回显(repolist: 16771 即恢复成功;完整过程回显见 2.4.3):

repo id                     repo name                                     status
base                        CentOS-7.9.2009 - Base                        10072
extras                      CentOS-7.9.2009 - Extras                        526
updates                     CentOS-7.9.2009 - Updates                      6173
repolist: 16771

需要 EPEL 小工具时再叠加 2.4.5 的 epel-release 安装与 sed 固定,四源总盘 30562 个包。

4.2 场景二:演示包全生命周期闭环(search → install → update → downgrade → remove → autoremove)

以 geoipupdate 走完一圈(本场景的 6 条命令在 3.x 各节实测后的环境上完整真实执行,回显逐字照抄):

yum search geoipupdate                 # ① 找包
yum install -y geoipupdate             # ② 装
yum update -y geoipupdate              # ③ 升级(对已最新包执行 update 会如何)
yum downgrade -y geoipupdate           # ④ 降级回 base GA 版(归档源保留旧版)
yum remove -y geoipupdate              # ⑤ 卸载
yum autoremove                         # ⑥ 清孤儿依赖

① search 命中两条(N/S 匹配):

=========================== N/S matched: geoipupdate ===========================
geoipupdate.x86_64 : Update GeoIP2 and GeoIP Legacy binary databases from
                   : MaxMind
geoipupdate-cron.noarch : Cron job to do weekly updates of GeoIP databases

  Name and summary matches only, use "search all" for everything.

② install 直接取源内最新版 2.5.0-2(与 3.3 的语境区别:装机时刻预装的包停在 2.5.0-1,而全新 install 永远拿 updates 里的最新版本):

$ yum install -y geoipupdate
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package geoipupdate.x86_64 0:2.5.0-2.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package             Arch           Version               Repository       Size
================================================================================
Installing:
 geoipupdate         x86_64         2.5.0-2.el7           updates          35 k

Transaction Summary
================================================================================
Install  1 Package
...
  Installing : geoipupdate-2.5.0-2.el7.x86_64                               1/1
  Verifying  : geoipupdate-2.5.0-2.el7.x86_64                               1/1

Installed:
  geoipupdate.x86_64 0:2.5.0-2.el7

Complete!

③ 对已是最新的包执行 update:不报错、不产生事务、退出码 0(注意与 install 的 already installed and latest version / Nothing to do 措辞不同):

$ yum update -y geoipupdate
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
No packages marked for update

④ downgrade 降回 base 源保留的 GA 版 2.5.0-1(事务结构与 3.4 完全一致,表头节选):

---> Package geoipupdate.x86_64 0:2.5.0-1.el7 will be a downgrade
---> Package geoipupdate.x86_64 0:2.5.0-2.el7 will be erased
...
Downgrading:
 geoipupdate          x86_64          2.5.0-1.el7           base           35 k

Transaction Summary
================================================================================
Downgrade  1 Package

⑤ remove 卸载后复核:

Removing:
 geoipupdate          x86_64          2.5.0-1.el7          @base           61 k
...
  Erasing    : geoipupdate-2.5.0-1.el7.x86_64                               1/1

Removed:
  geoipupdate.x86_64 0:2.5.0-1.el7

Complete!
$ rpm -q geoipupdate
package geoipupdate is not installed

⑥ 当前已无 dep 标记孤儿,autoremove 空跑的真实输出(也是一次安全检查):

$ yum autoremove
Loaded plugins: fastestmirror, ovl
No Packages marked for removal

全生命周期实测状态链(每步之后 rpm -q geoipupdate 的真实结果):

节点rpm -q 结果说明
② install 后geoipupdate-2.5.0-2.el7.x86_64install 取源内最新
③ update 后geoipupdate-2.5.0-2.el7.x86_64No packages marked for update
④ downgrade 后geoipupdate-2.5.0-1.el7.x86_64依赖归档源保留 GA 版
⑤ remove 后package geoipupdate is not installed干净卸载

要点:④ 能成功归功于归档源保留 GA 版本;⑥ 提醒——当系统存在 dep 标记的遗留包时,autoremove 会把 hostname/bc 这类基础包一并圈入(3.13 的实测案例),生产上务必先看预览清单再决定是否 -y。

4.3 场景三:升级巡检与事务回滚(check-update → update → history undo)

日常巡检三件套 + 出问题时的一键回滚:

yum check-update; echo "退出码=$?"     # 0 无更新 / 100 有更新 / 1 出错
yum check                              # rpmdb 一致性体检(实测输出 check all,退出码 0)
yum history list | head -8             # 最近事务一览

实测回显(巡检段):

Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile

bash.x86_64                        4.2.46-35.el7_9                       updates
...
(51 个可升级包,节选)
100        ← 退出码=100,有更新

Loaded plugins: fastestmirror, ovl
check all

升级前先记下事务 ID(如 yum history list 最新一条为 N),升级后出问题用 yum -y history undo N 整体回滚(完整回显见 3.12)——比手工挑选旧版本 rpm 可靠得多。

4.4 场景四:离线安装包制备与独立根验证

联网机上为一批同版本 CentOS 7 目标机制备安装包,再在离线机或独立根里验证:

# 联网机:只下载,连带依赖
mkdir -p /root/dl
yum install -y --downloadonly --downloaddir=/root/dl zsh

# 目标机:本地 rpm 安装(Repository 列显示 /本地路径,见 3.15)
yum install -y /root/dl/zsh-5.0.2-34.el7_8.2.x86_64.rpm

# 独立根验证:不污染宿主 rpmdb(完整回显见 3.16)
yum --installroot=/root/testroot --releasever=7 install -y epel-release
ls /root/testroot/etc/yum.repos.d/
rm -rf /root/testroot

downloadonly 的实测产物:

$ ls -lh /root/dl/
total 2.4M
-rw-r--r-- 1 root root 2.4M Apr  8  2020 zsh-5.0.2-34.el7_8.2.x86_64.rpm

要点:downloadonly 只下载「本次解析到的包」,目标机若缺其他依赖,把依赖包名一并写进同一条 downloadonly 命令即可(yum 会一起解析下载)。

4.5 场景五:缓存磁盘治理(clean 家族分级清理)

/var/cache/yum 随使用膨胀(本文四源实测累计 654M),磁盘告警时按需清理:

du -sh /var/cache/yum          # 清理前基线
yum clean packages             # 只删 rpm 包文件(最保守)
yum clean metadata             # 删元数据(下次命令重新拉取)
yum clean all                  # 全清(等价 packages+metadata+dbcache+plugins)
du -sh /var/cache/yum          # 清理后复核

实测前后对比(完整分级回显见 3.11):

654M	/var/cache/yum     ← 清理前(含 keepcache 保留的包 + 四源元数据/数据库)
64K	/var/cache/yum      ← yum clean all 之后

要点:清完 immediately yum makecache 重建索引可避免下一个用户的命令卡在元数据下载上;clean packages 只回收包文件、保留元数据,是「只想要点空间、不想损失命令速度」的折中选项。

五、注意事项与常见问题

Q1:yum 任何命令都报 Could not resolve host: mirrorlist.centos.org,怎么办? 这是 CentOS 7 于 2024-06-30 EOL 后的必然现象,官方列表服务已停止解析。修复三步(完整实录见 2.4.1-2.4.3):① 备份 mkdir -p /etc/yum.repos.d/backup && mv /etc/yum.repos.d/CentOS-*.repo /etc/yum.repos.d/backup/;② 新写 /etc/yum.repos.d/CentOS-Base.repo,三个启用小节 baseurl 固定到阿里云归档 http://mirrors.aliyun.com/centos-vault/7.9.2009/{os,updates,extras}/x86_64/(注意用具体版本号 7.9.2009 而不是 $releasever=7);③ yum clean all && yum makecache && yum repolist 验证到 repolist: 16771。不想新写文件可用 2.4.4 的 sed 批改原文件,效果等价。

Q2:官方归档 vault.centos.org 能用吗?实测返回 403。 本文实测 https://vault.centos.org/7.9.2009/os/x86_64/ 返回 403(官方归档对部分网络/地区有限制),并非配置错误。替代方案:阿里云归档 mirrors.aliyun.com/centos-vault/7.9.2009/...(实测 200,本文采用)、清华 TUNA 等高校归档站的 centos-vault 目录,或 2.4.2 探测命令实测通过的其他归档站。判断标准就一条:curl -sI <url>/repodata/repomd.xml 返回 200 即可用作 baseurl。

Q3:安装时报 NOKEY / Public key for xxx.rpm is not installed,正常吗? gpgcheck=1 下首次安装某源的包,yum 会自动从 repo 的 gpgkey= 路径导入公钥并在输出里展示指纹(3.1 实测导入了 CentOS-7 Key f4a80eb5)。这条 warning 只在密钥尚未导入时出现一次,导入成功则安装继续,属正常流程。真正的危险信号是「导入的指纹与官方公布不符」或「反复要求导入同一密钥」——后者通常是 repo 文件被改动过 gpgkey 路径。临时绕过用 --nogpgcheck,仅限可信内网源。

Q4:yum autoremove 把 hostname、bc 这些系统包都删了,是不是有 bug? 不是 bug,是 reason=dep 标记机制在起作用(3.13 实测):这些包在装机/系统构建阶段被标记为「依赖自动拉入」,且当前没有包依赖它们,autoremove 按规则就会清理。对策:① 每次执行前逐行读预览清单(不带 -y 先看);② 误圈的基础包执行 yumdb set reason user 包名 后再 autoremove;③ 事后补救用 yum history 找到 autoremove 的事务 ID,yum -y history undo <ID> 整体回滚(前提:被删包仍在源中——归档源满足)。

Q5:yum list xxx | head 时总出现 Exiting on Broken Pipe,有问题吗? 没有。head 读完前几行即退出关闭管道,yum 继续写输出时收到 SIGPIPE 主动退出并打印这句(3.8 实测两处)。想避免就在脚本里不用 head 截断实时输出,改为先落盘再取:yum list installed > /tmp/list.txt && head /tmp/list.txt;或对 yum 加 -q 减少无谓输出。

Q6:yum group list 前面总提示 There is no installed groups file. Maybe run: yum groups mark convert,要处理吗? 这是最小安装机上的常见提示:系统没有组标记文件,yum 只是提醒、不影响 group list/info 使用(3.18 实测带提示照常输出)。按提示执行 yum groups mark convert(实测回显 Converted old style groups to objects.)即消除,此后 group list 会显示 Installed Groups: 段。不处理也完全不影响 group install/remove。

Q7:EPEL 源报 curl#35 - "Peer reports incompatible or unsupported protocol version." 怎么回事? EPEL 7 归档站点里混有只支持新版 TLS 的站点,而 CentOS 7 自带的 NSS 库较老,TLS 版本协商不上就报这个错(2.4.5 实测:fastestmirror 换站点重试后成功,但不可预期)。治本方案与官方源同理:metalink/mirrorlist 注释掉,baseurl 固定到阿里云 EPEL 归档 http://mirrors.aliyun.com/epel-archive/7/x86_64,一劳永逸。

Q8:repolist 显示 status 全是 0,或报 Cannot find a valid baseurl for repo: base/7/x86_64? status 0 = 该源元数据为空:要么 mirrorlist 失效拉不到列表(Q1),要么 baseurl 路径写错(如把 $releasever=7 拼进了归档路径,归档只认 7.9.2009)。排查顺序:yum -v repolist 看 Repo-baseurl 实际取值(3.10)→ curl -sI <baseurl>/repodata/repomd.xml 验证 URL → 修正后 yum clean all && yum makecache。Cannot find a valid baseurl 则说明源连「降级自救」都做不了,直接按 Q1 修复。

Q9:yum downgrade 报 Only Upgrade available on package xxx,为什么降不了级? downgrade 要求比当前低的版本仍存在于启用的源中。常规在线源只保留每包最新版,升上去就回不来(3.4 要点)。可行解:① 用保留历史版本的归档源(centos-vault 天然含 GA 版,本文实测成功);② 更可靠的是 yum history undo 升级事务ID——它按事务反演,不依赖旧版是否在源里(但也要求源可提供原版本包);③ 离线场景从 vault 手工下载旧版 rpm 后 yum install ./旧版.rpm 本地降级。

Q10:生产环境固化建议(EOL 时代 CentOS 7 版)。 ① 软件源一律固定 baseurl 到可用归档站,禁用 mirrorlist/metalink(2.4 实测依据);② 自动化脚本统一 -y 并检查退出码(check-update 的 100/0/1 三态见 3.5);③ 改动类操作前 yum history list | head -3 记下最新事务 ID,留好回滚锚点;④ autoremove 永远先预览、后执行,关键基础包先 yumdb set reason user;⑤ 内核/glibc/openssl 升级后重启或重启服务才算生效;⑥ 长期规划上尽早制定迁移计划(RHEL 7 同源变体 / Rocky / AlmaLinux / openEuler),EOL 系统的安全补丁已冻结在 2024-06,归档源只保「能用」不保「安全」。

六、参考链接