跳到主要内容

自动化巡检

巡检脚本示例

daily-inspection.sh
#!/usr/bin/env bash
set -euo pipefail

REPORT_FILE="/tmp/inspection-$(date +%Y%m%d).md"

cat > "$REPORT_FILE" << EOF
# 日常巡检报告 - $(date '+%Y-%m-%d %H:%M')
---
EOF

# 系统负载
echo "## 系统负载" >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"
uptime >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"

# 内存使用
echo "## 内存使用" >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"
free -h >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"

# 磁盘使用(筛选超过 80% 的分区)
echo "## 磁盘告警(>80%)" >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"
df -h | awk 'NR==1 || +$5 > 80' >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"

# 关键服务状态
echo "## 服务状态" >> "$REPORT_FILE"
for svc in nginx mysql redis docker; do
status=$(systemctl is-active "$svc" 2>/dev/null || echo "not-found")
echo "- $svc: **$status**" >> "$REPORT_FILE"
done

# 最近失败的 systemd 服务
echo "## 失败的服务" >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"
systemctl --failed --no-pager >> "$REPORT_FILE"
echo '```' >> "$REPORT_FILE"

echo "Report saved to $REPORT_FILE"

Ansible 巡检 Playbook

inspection.yml
---
- name: Daily Server Inspection
hosts: all
gather_facts: yes
become: yes

tasks:
- name: Check disk usage
shell: df -h | awk '$5+0 > 80 {print}'
register: disk_alert
changed_when: false

- name: Report disk alert
debug:
msg: "⚠️ {{ inventory_hostname }}: {{ disk_alert.stdout_lines }}"
when: disk_alert.stdout | length > 0

- name: Check failed services
shell: systemctl --failed --no-legend | wc -l
register: failed_count
changed_when: false

- name: Report failed services
debug:
msg: "❌ {{ inventory_hostname }}: {{ failed_count.stdout }} failed services"
when: failed_count.stdout | int > 0

- name: Check NTP sync
shell: timedatectl | grep "synchronized" | awk '{print $NF}'
register: ntp_sync
changed_when: false

- name: Alert NTP not sync
debug:
msg: "⚠️ {{ inventory_hostname }}: NTP not synchronized"
when: ntp_sync.stdout != "yes"

巡检项清单

类别检查项告警阈值
CPU负载、使用率负载 > 核数 × 2
内存使用率、Swap使用 > 85%、Swap > 0
磁盘使用率、inode使用 > 80%、inode > 80%
网络丢包、延迟丢包 > 1%、延迟 > 100ms
服务进程存活、端口监听不可达
安全登录失败、可疑进程失败 > 10 次/小时
证书SSL 过期时间< 30
备份最后备份时间超过 24 小时

常见面试问题

Q1: 如何设计一套完整的自动化巡检体系?

答案

  1. 采集层:Shell/Ansible 脚本定期采集系统指标和服务状态
  2. 存储层:结果写入数据库或发送到 Prometheus
  3. 展示层:Grafana 看板展示巡检概览
  4. 告警层:异常指标自动发送钉钉/邮件通知
  5. 报告层:每天/每周生成巡检报告并归档

关键原则:定义明确的阈值可追溯历史数据异常自动通知

相关链接