1. 项目背景与核心价值
最近在运维工作中发现一个痛点:每次服务器巡检都需要手动执行十几条命令,检查CPU、内存、磁盘、网络等基础指标。这种重复劳动既耗时又容易遗漏关键指标。正好看到Claude Code这个AI编程助手的演示视频,决定尝试让它帮我写个自动化健康检查的Skill。
Claude Code是Anthropic公司推出的AI编程工具,它能够理解自然语言描述的需求并生成可运行的代码。与传统的代码补全工具不同,Claude Code特别适合快速开发小型功能模块(他们称之为"Skill")。我花了大约2小时与它交互调试,最终产出的运维检查工具已经稳定运行了三周,效果超出预期。
这个Skill的核心功能包括:
- 自动收集服务器基础指标(CPU/内存/磁盘使用率)
- 检测关键服务进程状态
- 检查网络连通性
- 生成可视化报告
- 异常阈值告警
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 开发环境准备与Claude Code配置
2.1 基础环境搭建
首先需要准备Python 3.8+环境,这是Claude Code目前主要支持的语言。建议使用virtualenv创建隔离环境:
bash复制python -m venv claude_env
source claude_env/bin/activate # Linux/Mac
# 或 claude_env\Scripts\activate # Windows
安装Claude Code的VS Code插件:
- 打开VS Code扩展市场
- 搜索"Claude Code"
- 安装官方插件(注意识别Anthropic官方出品)
- 重启VS Code后侧边栏会出现Claude图标
注意:部分区域可能需要特殊网络配置才能访问Claude服务。如果遇到连接问题,可以尝试检查本地代理设置或联系网络管理员。
2.2 Skill项目初始化
在VS Code中新建目录,通过Claude面板输入:
code复制/create skill named ops_health_check
这会生成基础项目结构:
code复制ops_health_check/
├── skill.yaml # Skill元数据
├── main.py # 主逻辑文件
└── test/
└── test_main.py # 测试用例
编辑skill.yaml配置基础信息:
yaml复制name: ops_health_check
version: 0.1.0
description: Automated server health check tool
entry_point: main.py
requirements:
- psutil>=5.8.0
- requests>=2.26.0
3. 核心功能开发过程
3.1 系统指标采集模块
向Claude Code输入提示词:
code复制帮我写一个Python函数,使用psutil获取以下系统指标:
- CPU使用率(1秒间隔)
- 内存使用率(包括swap)
- 磁盘使用率(所有挂载点)
- 最近1/5/15分钟负载
函数返回结构化的字典数据
生成的代码经过微调后:
python复制import psutil
def get_system_metrics():
metrics = {
'cpu': {
'percent': psutil.cpu_percent(interval=1),
'load_avg': [x / psutil.cpu_count() for x in psutil.getloadavg()]
},
'memory': {
'total': psutil.virtual_memory().total,
'available': psutil.virtual_memory().available,
'percent': psutil.virtual_memory().percent,
'swap': psutil.swap_memory().percent
},
'disks': []
}
for part in psutil.disk_partitions():
if part.fstype: # 忽略特殊文件系统
usage = psutil.disk_usage(part.mountpoint)
metrics['disks'].append({
'mount': part.mountpoint,
'total': usage.total,
'used': usage.used,
'percent': usage.percent
})
return metrics
3.2 服务状态检查模块
通过Claude Code补充服务检测逻辑:
python复制import subprocess
def check_service(service_name):
try:
# 适配不同Linux发行版
if subprocess.run(['which', 'systemctl'],
stdout=subprocess.PIPE).returncode == 0:
cmd = ['systemctl', 'is-active', service_name]
else:
cmd = ['service', service_name, 'status']
result = subprocess.run(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)
return 'active' in result.stdout.lower()
except Exception as e:
print(f"Check service error: {e}")
return False
3.3 网络连通性测试
Claude Code生成的网络检查模块需要手动优化重试逻辑:
python复制import socket
import requests
from urllib.parse import urlparse
def network_check(targets):
results = {}
for name, target in targets.items():
if target.startswith(('http://', 'https://')):
# HTTP检查
try:
r = requests.head(target, timeout=5)
results[name] = r.status_code < 400
except:
results[name] = False
else:
# 端口检查
try:
host, port = target.split(':')
with socket.create_connection((host, int(port)), timeout=5):
results[name] = True
except:
results[name] = False
return results
4. 功能集成与异常处理
4.1 主逻辑编排
将各模块组合成完整工作流:
python复制def health_check(config):
report = {
'timestamp': datetime.now().isoformat(),
'system': get_system_metrics(),
'services': {},
'network': network_check(config['network_targets'])
}
for service in config['monitored_services']:
report['services'][service] = check_service(service)
# 阈值检查
report['alerts'] = check_thresholds(report, config['thresholds'])
return report
4.2 告警阈值实现
Claude Code最初生成的阈值检查不够灵活,改进后:
python复制def check_thresholds(report, thresholds):
alerts = []
# CPU检查
if report['system']['cpu']['percent'] > thresholds.get('cpu', 90):
alerts.append(f"CPU使用率过高: {report['system']['cpu']['percent']}%")
# 内存检查
if report['system']['memory']['percent'] > thresholds.get('memory', 85):
alerts.append(f"内存使用率过高: {report['system']['memory']['percent']}%")
# 磁盘检查
for disk in report['system']['disks']:
if disk['percent'] > thresholds.get('disk', 90):
alerts.append(f"磁盘 {disk['mount']} 使用率过高: {disk['percent']}%")
# 服务检查
for name, status in report['services'].items():
if not status:
alerts.append(f"服务 {name} 未运行")
return alerts
5. 部署与使用实践
5.1 配置管理
创建config.yaml配置文件:
yaml复制monitored_services:
- nginx
- postgresql
- redis-server
network_targets:
google_dns: '8.8.8.8:53'
internal_api: 'https://api.internal.com/health'
thresholds:
cpu: 85
memory: 80
disk: 90
5.2 定时执行方案
使用systemd timer实现定时检查(Claude Code生成的单元文件需要手动调整):
/etc/systemd/system/ops-health-check.service:
ini复制[Unit]
Description=Ops Health Check Skill
After=network.target
[Service]
Type=oneshot
ExecStart=/path/to/venv/bin/python /path/to/main.py
User=ops
EnvironmentFile=/etc/default/ops-health-check
/etc/systemd/system/ops-health-check.timer:
ini复制[Unit]
Description=Run health check every 15 minutes
[Timer]
OnCalendar=*:0/15
Persistent=true
[Install]
WantedBy=timers.target
启用服务:
bash复制sudo systemctl daemon-reload
sudo systemctl enable --now ops-health-check.timer
5.3 结果可视化
Claude Code生成的HTML报告模板经过美化后:
python复制def generate_html(report):
return f"""
<!DOCTYPE html>
<html>
<head>
<title>Health Report - {report['timestamp']}</title>
<style>
.alert {{ color: red; font-weight: bold; }}
table {{ border-collapse: collapse; width: 100%; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
tr:nth-child(even) {{ background-color: #f2f2f2; }}
</style>
</head>
<body>
<h1>System Health Report</h1>
<p>Generated at: {report['timestamp']}</p>
{''.join(f'<p class="alert">{alert}</p>' for alert in report['alerts'])}
<h2>CPU</h2>
<p>Usage: {report['system']['cpu']['percent']}%</p>
<p>Load Average: {', '.join(f'{x:.2f}' for x in report['system']['cpu']['load_avg'])}</p>
<h2>Memory</h2>
<p>Usage: {report['system']['memory']['percent']}%</p>
<p>Swap: {report['system']['memory']['swap']}%</p>
<h2>Disks</h2>
<table>
<tr><th>Mount</th><th>Used</th><th>Total</th><th>Percent</th></tr>
{"".join(
f"<tr><td>{d['mount']}</td><td>{d['used']/1024/1024:.1f}MB</td>"
f"<td>{d['total']/1024/1024:.1f}MB</td><td>{d['percent']}%</td></tr>"
for d in report['system']['disks']
)}
</table>
<h2>Services</h2>
<ul>
{"".join(
f"<li>{name}: {'✅' if status else '❌'}</li>"
for name, status in report['services'].items()
)}
</ul>
</body>
</html>
"""
6. 实际使用中的经验总结
经过三周的实践运行,这个自动生成的运维检查Skill已经成功捕获了4次潜在问题。以下是几个关键经验:
-
指标采样频率优化:最初设置的1秒CPU采样在高负载场景会导致检查耗时过长,调整为3秒后取得更好平衡。
-
服务检测兼容性:发现systemctl检测在某些容器环境中不可用,增加了fallback到pgrep的检测逻辑:
python复制def check_service(service_name):
# ...原有检测逻辑...
if result is None: # 前两种方法都失败时
try:
subprocess.run(['pgrep', '-f', service_name], check=True)
return True
except:
return False
- 网络检查的DNS缓存问题:发现连续的网络检查可能受到DNS缓存影响,在network_check函数开头添加:
python复制socket.gethostbyname.cache_clear() # 清除DNS缓存
- 告警风暴抑制:当某个服务频繁启停时会导致告警刷屏,增加了简单的告警冷却机制:
python复制alert_cooldown = {} # 全局变量
def check_thresholds(report, thresholds):
global alert_cooldown
alerts = []
now = time.time()
# CPU检查示例
if (report['system']['cpu']['percent'] > thresholds.get('cpu', 90)
and now - alert_cooldown.get('cpu', 0) > 300): # 5分钟冷却
alerts.append(f"CPU使用率过高: {report['system']['cpu']['percent']}%")
alert_cooldown['cpu'] = now
# ...其他检查...
- 日志轮转配置:Claude Code没有自动生成日志管理配置,手动添加了logrotate配置:
bash复制/path/to/health_check.log {
daily
rotate 7
compress
missingok
notifempty
}
这个项目最让我惊讶的是,Claude Code不仅能生成可运行的代码,还能理解运维场景的特殊需求。比如当我说"需要考虑容器环境的特殊情况"时,它能主动建议使用/proc文件系统作为fallback检测方案。当然,最终的实现还是需要人工审核和调整,但至少节省了70%的基础编码时间。
