Linux 伺服器

AI 伺服器日報:用 Ollama 本地大模型分析日誌,每天自動推送到 Telegram

6 個步驟 11 分鐘閱讀 12 次閱讀 0
本文目錄

監控工具能告訴你伺服器或網站什麼時候宕機,但很多早期預警藏在日誌裡:磁碟每天都比前一天更滿一點、同一個錯誤重複出現幾百次、一波 SSH 暴力破解嘗試、某個程序悄悄吃掉 CPU。很少有人每天早上去翻這些日誌。本文每天收集一次關鍵資料,交給 Ollama 中的本地大模型整理成一份簡短易讀、附帶排查建議的日報,並推送到 Telegram。由於模型執行在你自己的伺服器上,日誌不會離開伺服器。

AI 日報只是每日概覽,既不是即時監控,也不是安全工具。宕機告警仍需正規的監控方案(參見使用 Uptime Kuma 監控併傳送 Telegram 告警),日報中標記出的問題也請親自核實:大模型可能會誤讀資料。

步驟 1:準備 Ollama、jq 和 Telegram 機器人

你需要按照使用 Ollama 部署本地大模型裝好 Ollama 和一個小模型,另外還需要 jq 和 curl。在 Telegram 中通過 @BotFather 建立機器人,先給它傳送任意一條訊息,再查詢你的 chat ID:

apt install -y jq curl
ollama pull qwen2.5:7b

# Send any message to your bot first, then:
curl -s "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates" | jq '.result[].message.chat.id'

步驟 2:建立日報指令碼

mkdir -p /opt/aireport
cat > /opt/aireport/report.sh <<'EOF2'
#!/bin/bash
# Daily AI server report: collect facts, summarise them with Ollama, send to Telegram
MODEL="qwen2.5:7b"
LANGUAGE="Simplified Chinese"                 # language of the report
TG_TOKEN="123456789:replace-with-your-bot-token"
TG_CHAT="123456789"
FACTS=/opt/aireport/facts.txt

{
  echo "Host: $(hostname)  Uptime: $(uptime -p)"
  echo "Load average 1/5/15 min: $(cut -d' ' -f1-3 /proc/loadavg)  CPU cores: $(nproc)"
  echo; echo "## Memory"; free -h
  echo; echo "## Disk usage"; df -h -x tmpfs -x devtmpfs -x overlay
  echo; echo "## Failed systemd units"; systemctl --failed --no-legend
  echo; echo "## Most frequent error messages in the last 24 hours"
  journalctl --since "24 hours ago" -p err --no-pager -o cat | sort | uniq -c | sort -rn | head -20
  echo; echo "## Failed SSH password logins in the last 24 hours (count, then top source IPs)"
  journalctl --since "24 hours ago" --no-pager -o cat | grep -c "Failed password"
  journalctl --since "24 hours ago" --no-pager -o cat | grep -oP "Failed password .* from \K[0-9a-fA-F.:]+" | sort | uniq -c | sort -rn | head -5
  if [ -f /var/log/nginx/access.log ]; then
    echo; echo "## Nginx HTTP status codes since the last log rotation"
    awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -8
    echo; echo "## URLs with the most 5xx errors"
    awk '$9 ~ /^5/ {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -5
  fi
  echo; echo "## Top processes by CPU"
  ps -eo user,pid,%cpu,%mem,etime,comm --sort=-%cpu | head -8
} > "$FACTS" 2>&1

PROMPT="You are an experienced Linux operations engineer. Below are today's facts from a server.
Write a short daily report in $LANGUAGE for the server owner:
1. First line: overall status, one of OK / ATTENTION / PROBLEM.
2. Then at most 5 bullet points about anything unusual, each with the likely cause and one command to check it.
3. If everything looks normal, say so in one sentence.
Only use the facts below. Do not invent numbers.

$(head -c 12000 "$FACTS")"

REPORT=$(jq -n --arg m "$MODEL" --arg p "$PROMPT" \
  '{model: $m, prompt: $p, stream: false, options: {temperature: 0.2, num_ctx: 8192}}' \
  | curl -s --max-time 900 http://127.0.0.1:11434/api/generate -d @- | jq -r '.response // empty')
[ -z "$REPORT" ] && REPORT="AI summary failed. Raw facts:
$(head -c 3000 "$FACTS")"

curl -s -X POST "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \
  --data-urlencode "chat_id=${TG_CHAT}" \
  --data-urlencode "text=[$(hostname)] daily report
${REPORT:0:3800}" > /dev/null
EOF2
chmod 700 /opt/aireport/report.sh

請把機器人 Token 和 chat ID 替換成你自己的。由於指令碼中包含 Token,因此設定為只有 root 能讀取。num_ctx 讓模型有足夠的上下文容納完整的資料清單,日報內容會被截斷,以符合 Telegram 的單條訊息長度限制。如果模型沒有返回結果,你仍會收到原始資料。

步驟 3:測試

/opt/aireport/report.sh
cat /opt/aireport/facts.txt      # the data the model saw

首次執行需要載入模型,耗時會長一些。多對比幾次日報和 facts.txt,判斷摘要對你的伺服器是否可靠;如果模型反應過度或不夠敏感,請調整提示詞。

步驟 4:設定每天定時傳送

echo '0 8 * * * root /opt/aireport/report.sh' > /etc/cron.d/aireport
timedatectl | grep "Time zone"     # cron uses the server's time zone

步驟 5:新增你關心的檢查項

在指令碼的花括號程式碼塊內新增更多段落,它們輸出的所有內容都會成為資料的一部分。下面是一些實用的示例:

  echo; echo "## Fail2ban"; fail2ban-client status sshd | grep -E "Currently banned|Total banned"
  echo; echo "## Stopped Docker containers"; docker ps -a --filter status=exited --format "{{.Names}}: {{.Status}}"
  echo; echo "## Certificates"; for c in /etc/letsencrypt/live/*/cert.pem; do echo "$c $(openssl x509 -enddate -noout -in "$c")"; done
  echo; echo "## Last backup file"; ls -lt /backup | head -3

相關教程:使用 Fail2ban 保護 SSH 和 Nginx、免費 SSL 證書申請與自動續期;如果租用了 IP 段,請參閱自動監控租用的 IP 段。

步驟 6:多台伺服器

不需要每台伺服器都執行 Ollama。各臺伺服器只執行資料收集部分,再把 facts.txt 複製到裝有 Ollama 的伺服器(例如在 cron 中使用 SSH 金鑰執行 scp),在那裡統一生成所有日報。如果改為直接呼叫集中部署的 Ollama,請通過內網或 VPN 訪問,切勿把 11434 埠開放到公網。

常見問題

生成一份日報要好幾分鐘?

在 CPU 上模型輸出較慢,對於每天執行一次的任務來說沒有問題。如果想更快生成日報,可以換用 qwen2.5:3b 等更小的模型,或刪除不需要的段落來精簡資料清單。

能否用雲端 AI API 代替本地模型?

技術上可以,但日誌中包含 IP 地址、使用者名稱、URL,有時還有客戶資料。把這些資料傳送給第三方會涉及隱私問題,並且必須遵守服務商的條款和支援地區。使用本地模型可以避免這些問題。

日報提示有異常,接下來該怎麼辦?

執行日報中建議的命令,並檢視原始資料。如果發現未知程序佔用大量 CPU 或出現異常登入,請按照如何判斷 Linux 伺服器是否被入侵進行排查。

如果按以上步驟操作後問題仍未解決,請提交工單聯絡 IMIDC 7×24 技術支援,並附上伺服器 IP、系統版本、facts.txt 的內容以及你收到的日報,方便工程師快速定位。

這篇文章有幫助嗎?

相關教程