温馨提示×

ubuntu定时生成报告技巧

小樊
34
2025-11-16 15:40:11
栏目: 智能运维

Ubuntu 定时生成报告实用技巧

一 核心方案 cron 定时与日志排查

  • 使用 crontab -e 编辑当前用户的计划任务,基本格式为:分 时 日 月 周 命令。示例:每天 01:00 执行脚本为 0 1 * * * /path/to/script.sh;每小时执行为 **0 * * * ***。保存后任务即生效。
  • 常用管理命令:crontab -l 查看任务,service cron status 查看服务状态,sudo service cron start 启动服务(如未运行)。
  • 排查要点:编辑 /etc/rsyslog.d/50-default.conf,取消注释 cron. /var/log/cron.log*,重启 rsyslog 后,用 tail -f /var/log/cron.log 实时查看定时任务执行情况与报错。
  • 环境建议:在脚本中显式设置环境变量(如 PATH、HOME、LANG),避免因 cron 环境精简导致命令找不到。

二 报告内容快速采集命令

  • 系统资源报告(CPU/内存/磁盘等):安装 sysstat 后使用 cpustat。示例:生成一次简要报告 sudo cpustat -u > cpustat_report.txt;间隔采样 sudo cpustat -u -w 5 -c 3 > cpustat_report.txt(每 5 秒一次,共 3 次)。
  • 日志分析报告:对应用日志做关键字统计,如 grep “ERROR” /var/log/nodejs/error.log | awk ‘{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10}’ > error_report.txt;也可结合 logwatch 做日/周报(如 sudo logwatch,可在 /etc/logwatch/conf/logwatch.conf 中设置 Detail、Range、Output、MailTo)。
  • 网络与代理流量:使用 Privoxycurl --stats 采集访问统计并写入报告,如 curl --stats http://example.com | tee /path/to/traffic_report.txt;配合 cron 每日固定时间生成。

三 报告分发与归档

  • 邮件发送:将报告通过本地 mail 命令发送,如 mail -s “Node.js Error Report” your_email@example.com < error_report.txt。如需 HTML 报告,可生成 HTML 文件后再发送。
  • 日志型报告:使用 logwatch 直接输出到邮件或文件,适合做 每日/每周 系统与应用日志摘要。
  • 命名与归档:建议按日期组织报告,如 /var/reports/$(date +%F).log;在脚本中使用 gzip 压缩归档,便于长期保存与传输。

四 可复用脚本模板

  • 模板示例(系统资源 + 错误日志 + 邮件)
#!/usr/bin/env bash
set -Eeuo pipefail

REPORT_DIR="/var/reports"
mkdir -p "$REPORT_DIR"
REPORT="$REPORT_DIR/$(date +%F).log"
TMP_ERR="/tmp/err_$(date +%s).txt"

# 0) 环境(cron 环境精简,建议显式设置)
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export LANG=en_US.UTF-8

# 1) 系统资源(需安装 sysstat)
if command -v cpustat >/dev/null 2>&1; then
  echo "===== CPU 使用报告 $(date) =====" >> "$REPORT"
  cpustat -u >> "$REPORT" 2>/dev/null || echo "cpustat 不可用或无权限" >> "$REPORT"
fi

# 2) 应用错误日志示例(按实际路径修改)
if [[ -f /var/log/nodejs/error.log ]]; then
  echo "===== 应用 ERROR 统计 $(date) =====" >> "$REPORT"
  grep -i "ERROR" /var/log/nodejs/error.log 2>/dev/null | head -n 200 >> "$REPORT" || echo "无 ERROR 记录" >> "$REPORT"
fi

# 3) 发送邮件(如未配置本地 MTA,可改为 scp/企业微信/钉钉 webhook)
if command -v mail >/dev/null 2>&1; then
  mail -s "系统日报 $(hostname) $(date +%F)" your_email@example.com < "$REPORT"
fi

# 4) 归档压缩
gzip -f "$REPORT"
  • 定时示例
    • 每天 01:00 生成并邮件发送:0 1 * * * /usr/local/bin/daily_report.sh
    • 6 小时采样一次资源:*0 /6 * * * /usr/local/bin/daily_report.sh
  • 权限与路径:涉及系统统计的命令(如 cpustat)可能需要 sudo;若以普通用户运行,可将脚本加入 sudoers 免密执行指定命令,或将输出目录改为用户可写路径(如 ~/reports)。

0