Files
Linux/debian/upgrade.sh

74 lines
2.1 KiB
Bash

#!/usr/bin/env bash
#
# ...
#
# 使用方法:
# URL="https://git.1-h.cc/Scripts/Linux/raw/branch/main/debian/upgrade.sh"; curl -fsSL "$URL" | bash || wget -q -O - "$URL" | bash
# 设置非交互式环境变量
export DEBIAN_FRONTEND=noninteractive
apt -qq update
# 安装自动更新
apt install -y unattended-upgrades
# 启用自动更新
dpkg-reconfigure -plow unattended-upgrades
# 配置自动更新并在凌晨2点自动重启
cat <<EOF | tee /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-WithUsers "true";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";
EOF
apt -qq upgrade -y
apt -qq full-upgrade -y
apt -qq autoremove
apt -qq autoclean
apt clean
systemctl --failed
apt -qq install needrestart -y
############################################
# 设置变量标记是否需要重启
NEEDS_REBOOT=0
REASONS=""
# 方法1: 检查 reboot-required 文件
if [ -f /var/run/reboot-required ]; then
NEEDS_REBOOT=1
# 如果有详细信息文件,显示需要重启的包
if [ -f /var/run/reboot-required.pkgs ]; then
REASONS="需要重启的包:\n$(cat /var/run/reboot-required.pkgs)"
else
REASONS="系统标记为需要重启"
fi
fi
# 方法2: 检查正在运行的内核与已安装的最新内核是否不同
CURRENT_KERNEL=$(uname -r)
LATEST_KERNEL=$(dpkg -l 'linux-image-*' | grep ^ii | grep -v "${CURRENT_KERNEL}" | sort -V | tail -n 1 | awk '{print $2}' | sed 's/linux-image-//')
if [ ! -z "$LATEST_KERNEL" ] && [ "$LATEST_KERNEL" != "$CURRENT_KERNEL" ]; then
NEEDS_REBOOT=1
REASONS="${REASONS}\n已安装新内核: ${LATEST_KERNEL},当前运行内核: ${CURRENT_KERNEL}"
fi
# 方法3: 使用 needrestart 工具(如果已安装)
if command -v needrestart &> /dev/null; then
if needrestart -b | grep -q "NEEDRESTART-KSTA: 1"; then
NEEDS_REBOOT=1
REASONS="${REASONS}\nneedrestart 工具表明需要内核重启"
fi
fi
# 输出结果
if [ $NEEDS_REBOOT -eq 1 ]; then
echo -e "系统需要重启\n原因:\n${REASONS}"
exit 1
else
echo "系统不需要重启"
exit 0
fi