Linux shell监控http脚本(Linux如何监控http服务)

在Shell中,可以使用curl或wget命令来监控HTTP服务。

以下是一个简单的Shell脚本,用于监控HTTP服务并在服务不可用时发送通知邮件。

首先确保已经安装了curl或wget。

#!/bin/bash # 变量设置 url="http://example.com" # 要监控的URL email="youremail@example.com" # 接收通知的邮箱 temp_file="/tmp/http_monitoring.log" # 临时文件存放位置 subject="HTTP Service Alert" # 邮件主题 # 检查curl或wget是否存在 if ! command -v curl &>/dev/null && ! command -v wget &>/dev/null; then echo "请先安装curl或wget" exit 1 fi # 发送邮件函数 send_email() { mail -s "${subject}" "${email}" < "${temp_file}" } # 使用curl或wget检查HTTP状态 if command -v curl &>/dev/null; then status_code=$(curl -o /dev/null -s -w "%{http_code}" "${url}") else status_code=$(wget -S --spider "${url}" 2>&1 | grep "HTTP/" | awk '{print $2}' | tail -1) fi # 判断HTTP状态 if [ "${status_code}" -eq 200 ]; then echo "HTTP服务正常,状态码:${status_code}" else echo "HTTP服务异常,状态码:${status_code}" > "${temp_file}" send_email fi
  1. 将此脚本保存为http_monitor.sh
  2. 用你的URL替换http://example.com
  3. 用你的电子邮件地址替换youremail@example.com
  4. 赋予脚本执行权限:chmod +x http_monitor.sh
  5. 执行脚本:./http_monitor.sh

注意:这个脚本会发送警报邮件,需要确保系统已经配置了邮件发送程序(如sendmail、postfix等)。如果需要定时监控,可以将脚本添加到cron定时任务中。

阅读剩余
THE END