You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xubuntu22.04/Raspbian OS实现unattended-upgrades的Telegram稳定通知

为unattended-upgrades配置Telegram通知方案

一、准备Telegram凭证

  • 创建Telegram机器人:联系@BotFather,发送/newbot按指引创建,获取Bot Token(格式类似123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11)
  • 获取Chat ID:给机器人发一条消息,然后调用API(替换你的Token):
    curl "https://api.telegram.org/bot<你的Bot Token>/getUpdates"
    
    从返回的JSON中找到message.chat.id对应的数值,就是你的Chat ID

二、编写安全的Telegram通知脚本

  1. 创建配置文件存储敏感信息(权限设为600,仅root可读):

    sudo nano /etc/telegram-upgrade-notify.conf
    

    写入内容:

    TELEGRAM_BOT_TOKEN="你的Bot Token"
    TELEGRAM_CHAT_ID="你的Chat ID"
    

    设置权限:

    sudo chmod 600 /etc/telegram-upgrade-notify.conf
    
  2. 创建通知脚本(放在/usr/local/bin/,避免系统升级被覆盖):

    sudo nano /usr/local/bin/telegram-upgrade-notify
    

    写入脚本内容:

    #!/bin/bash
    # 加载配置文件
    source /etc/telegram-upgrade-notify.conf
    
    # 读取邮件主题和内容(unattended-upgrades会通过管道传入)
    SUBJECT=$(head -n 1)
    CONTENT=$(cat)
    
    # 格式化消息内容,适配Telegram格式
    MESSAGE="⚠️ 系统升级通知\n**主机名**: $(hostname)\n**主题**: $SUBJECT\n\n**详情**:\n$CONTENT"
    
    # 调用Telegram API发送消息
    curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
      -d chat_id="${TELEGRAM_CHAT_ID}" \
      -d text="${MESSAGE}" \
      -d parse_mode="Markdown" > /dev/null 2>&1
    

    设置脚本可执行:

    sudo chmod +x /usr/local/bin/telegram-upgrade-notify
    

三、配置unattended-upgrades调用脚本

修改/etc/apt/apt.conf.d/50unattended-upgrades文件,调整通知相关配置:

sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

找到并修改以下配置(如果没有则添加):

# 禁用默认邮件通知(可选,若不需要邮件备份)
Unattended-Upgrade::Mail "";
# 指定使用我们的Telegram通知脚本替代sendmail
Unattended-Upgrade::MailCommand "/usr/local/bin/telegram-upgrade-notify";
# 开启升级通知(成功/失败都通知)
Unattended-Upgrade::NotifyOnUpgrade "true";
Unattended-Upgrade::NotifyOnFailure "true";

四、测试方案有效性

  1. 手动测试脚本:

    echo -e "测试主题\n这是一条测试升级通知内容" | sudo /usr/local/bin/telegram-upgrade-notify
    

    检查Telegram是否收到消息

  2. 测试unattended-upgrades的模拟运行:

    sudo unattended-upgrade --dry-run --debug
    

    若有可升级包,会触发通知(根据配置)

五、确保系统/发行版升级后稳定性

  • 脚本放在/usr/local/bin/:该目录属于用户自定义二进制文件目录,系统升级不会覆盖
  • 配置文件放在/etc/:发行版升级时会保留自定义配置(若提示覆盖,选择保留本地版本)
  • 备份关键配置:定期备份/etc/apt/apt.conf.d/50unattended-upgrades和/etc/telegram-upgrade-notify.conf

六、安全注意事项

  • 配置文件telegram-upgrade-notify.conf必须设为600权限,防止其他用户读取敏感凭证
  • 脚本仅允许root执行(默认创建后root拥有,无需额外设置)
  • curl调用添加-s参数静默执行,避免日志泄露敏感信息

内容的提问来源于stack exchange,提问作者Stackl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:54:36