应建立稳定、安全、可验证的自动化机制:ubuntu/debian用apt-autoremove+systemd timer,centos/rhel 8+用dnf autoremove+yum-utils限数,pve用proxmox-boot-tool+自定义脚本,并统一加入内核保留、空间阈值和grub校验等防护逻辑。

定期清理未使用的旧版内核,关键不是“手动删几次”,而是建立稳定、安全、可验证的自动化机制。不同发行版原生支持程度不同,但都能通过组合系统工具+定时任务实现可靠自动清理。
Ubuntu/Debian 系统:用 apt-autoremove + systemd timer
Ubuntu 原生的 apt autoremove --purge 已能智能识别并保留当前运行内核及上一个版本,适合日常维护。
要让它定期执行:
- 创建定时清理脚本(如 /usr/local/bin/clean-old-kernels.sh):
#!/bin/bash
apt update > /dev/null 2>&1
apt autoremove --purge -y > /dev/null 2>&1
update-grub > /dev/null 2>&1
- 赋予执行权限:sudo chmod +x /usr/local/bin/clean-old-kernels.sh
- 新建 systemd timer(/etc/systemd/system/kernel-clean.timer):
[Unit]
Description=Clean old kernels weekly
[Timer]
OnCalendar=weekly
Persistent=true
[Install]
WantedBy=timers.target
- 配套 service 文件(/etc/systemd/system/kernel-clean.service):
[Unit]
Description=Run kernel cleanup
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/clean-old-kernels.sh
StandardOutput=journal
- 启用并启动:sudo systemctl daemon-reload && sudo systemctl enable --now kernel-clean.timer
CentOS/RHEL 8+(DNF):用 dnf autoremove + yum-utils 自动限数
DNF 本身不带内核数量控制,但 yum-utils 提供了精准策略:
- 安装工具:sudo dnf install -y yum-utils
- 设置只保留最新 2 个内核(含当前运行):sudo dnf install -y yum-utils && sudo package-cleanup --oldkernels --count=2
- 将其写入 cron(每天检查一次):echo "0 2 * * 0 root /usr/bin/dnf autoremove -y && /usr/bin/package-cleanup --oldkernels --count=2" | sudo tee -a /etc/crontab
PVE(Proxmox VE):用 proxmox-boot-tool + 自定义脚本
PVE 使用 proxmox-boot-tool 管理启动内核,它默认保留当前 + 最新两个,但不会自动卸载旧包。
- 查看当前配置的启动内核:proxmox-boot-tool kernel list
- 列出所有已安装但未被 boot-tool 引用的 PVE 内核:dpkg -l | grep 'pve' | grep 'ii' | awk '{print $2}' | grep -E 'kernel-.*-pve' | grep -v "$(uname -r)" | sort -V | head -n -2
- 封装为一键清理脚本(加判断避免误删)后,加入 /etc/cron.weekly/ 目录即可每周自动运行。
通用加固建议
无论哪种方式,都应加入基础防护逻辑:
- 每次清理前记录当前内核:echo "$(date): running $(uname -r)" >> /var/log/kernel-clean.log
- 跳过清理若 /boot 分区使用率低于 30%(防误触发):[[ $(df /boot | tail -1 | awk '{print $5}' | sed 's/%//') -lt 30 ]] && exit 0
- 清理后校验 GRUB 配置是否更新:grep -q "$(uname -r)" /boot/grub/grub.cfg || update-grub











