您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Nagios页面监控脚本是怎么样的
## 引言
在企业级IT运维中,服务可用性监控是保障业务连续性的关键环节。Nagios作为开源监控系统的代表,其灵活的插件机制允许用户通过自定义脚本扩展监控能力。本文将深入探讨Nagios页面监控脚本的实现原理、典型架构和实际应用场景。
## 一、Nagios监控脚本基础概念
### 1.1 Nagios插件规范
Nagios脚本本质上遵循以下规范:
- 使用Bash/Python/Perl等脚本语言编写
- 返回标准化的退出状态码:
- 0:OK
- 1:WARNING
- 2:CRITICAL
- 3:UNKNOWN
- 输出第一行作为简短状态信息(显示在Dashboard)
- 可选的性能数据(用`|`分隔)
### 1.2 页面监控的特殊性
相比常规服务监控,网页监控需要处理:
- HTTP状态码验证(200/404/500等)
- 响应时间阈值
- 页面内容匹配(关键词/正则表达式)
- SSL证书有效期检查
## 二、典型脚本实现方案
### 2.1 Bash实现示例
```bash
#!/bin/bash
URL="https://example.com"
TIMEOUT=10
KEYWORD="Welcome"
response=$(curl -sSL --max-time $TIMEOUT -w "%{http_code}" -o /dev/null $URL)
code=$?
if [ $code -ne 0 ]; then
echo "CRITICAL: Connection failed (curl error $code)"
exit 2
elif [[ $response != 2* ]]; then
echo "CRITICAL: HTTP $response"
exit 2
else
if ! curl -sSL $URL | grep -q "$KEYWORD"; then
echo "WARNING: Keyword not found"
exit 1
fi
echo "OK: Page loaded successfully | time=${response_time}s"
exit 0
fi
#!/usr/bin/env python3
import requests
import sys
from urllib.parse import urlparse
def check_website(url, timeout=5, keyword=None):
try:
r = requests.get(url, timeout=timeout, verify=True)
r.raise_for_status()
if keyword and keyword not in r.text:
return (1, f"WARNING: Keyword '{keyword}' not found")
return (0, f"OK: {url} (HTTP {r.status_code}) | response_time={r.elapsed.total_seconds():.2f}s")
except requests.exceptions.SSLError as e:
return (2, f"CRITICAL: SSL Error - {str(e)}")
except requests.exceptions.RequestException as e:
return (2, f"CRITICAL: Connection failed - {str(e)}")
if __name__ == "__main__":
url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"
keyword = sys.argv[2] if len(sys.argv) > 2 else None
code, msg = check_website(url, keyword=keyword)
print(msg)
sys.exit(code)
模拟用户操作流程:
with requests.Session() as s:
# 登录检查
login = s.post(login_url, data=credentials)
if "Login Failed" in login.text:
return (2, "CRITICAL: Login failed")
# 仪表盘检查
dashboard = s.get(dashboard_url)
if dashboard.status_code != 200:
return (2, f"CRITICAL: Dashboard {dashboard.status_code}")
# 订单提交检查
order = s.post(order_api, json=order_data)
return (0, f"OK: Transaction completed in {order.elapsed.total_seconds():.2f}s")
Nagios支持将性能数据附加到输出:
OK: Page loaded | time=0.87s; size=245KB; uptime=99.98%
在Python中可通过:
perf_data = f"time={elapsed:.2f}s; size={len(content)/1024:.2f}KB"
print(f"OK: Status normal | {perf_data}")
/usr/local/nagios/libexec/
chmod +x /usr/local/nagios/libexec/check_website.py
chown nagios:nagios /usr/local/nagios/libexec/check_website.py
define command {
command_name check_website
command_line $USER1$/check_website.py $ARG1$ $ARG2$
}
define service {
use generic-service
host_name web-server
service_description Website Availability
check_command check_website!https://example.com!"Welcome"
normal_check_interval 5
retry_check_interval 1
}
故障类型 | 处理方案 |
---|---|
连接超时 | 设置合理的timeout值 |
SSL证书过期 | 提前30天告警 |
内容篡改 | 校验页面哈希或关键元素 |
流量突增 | 监控响应时间百分位数 |
NRPE
模式测试:
/usr/local/nagios/libexec/check_nrpe -H 127.0.0.1 -c check_website
import logging
logging.basicConfig(level=logging.DEBUG)
通过textfile
exporter暴露指标:
from prometheus_client import write_to_textfile
METRICS_FILE = '/var/lib/node_exporter/website.prom'
write_to_textfile(METRICS_FILE,
Gauge('website_response_seconds', 'HTTP response time').set(elapsed))
使用Ansible批量部署监控脚本:
- name: Deploy website monitor
template:
src: check_website.j2
dest: /usr/local/nagios/libexec/check_website.py
mode: 0755
owner: nagios
group: nagios
一个健壮的Nagios页面监控脚本需要兼顾准确性、性能和可维护性。通过合理设计状态判断逻辑、完善的异常处理以及标准化的输出格式,可以构建出适应复杂业务场景的监控解决方案。随着云原生技术的发展,建议结合Prometheus等现代监控工具形成立体化监控体系。
本文示例代码已托管至GitHub仓库:https://github.com/example/nagios-web-monitoring “`
注:实际文章约1650字,包含: - 6个主要章节 - 4个完整代码示例 - 2个配置示例 - 1个对比表格 - 标准Markdown格式(代码块、表格、标题等)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。