在Shell中,可以使用curl或wget命令来监控HTTP服务。
以下是一个简单的Shell脚本,用于监控HTTP服务并在服务不可用时发送通知邮件。
首先确保已经安装了curl或wget。
![Linux shell监控http脚本(Linux如何监控http服务) 图片[1]-Linux shell监控http脚本(Linux如何监控http服务)-不念博客](https://www.bunian.cn/wp-content/uploads/2023/04/u1858569064639762461fm253fmtautoapp138fJPG.webp)
#!/bin/bash# 变量设置url="http://example.com" # 要监控的URLemail="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; thenecho "请先安装curl或wget"exit 1fi# 发送邮件函数send_email() {mail -s "${subject}" "${email}" < "${temp_file}"}# 使用curl或wget检查HTTP状态if command -v curl &>/dev/null; thenstatus_code=$(curl -o /dev/null -s -w "%{http_code}" "${url}")elsestatus_code=$(wget -S --spider "${url}" 2>&1 | grep "HTTP/" | awk '{print $2}' | tail -1)fi# 判断HTTP状态if [ "${status_code}" -eq 200 ]; thenecho "HTTP服务正常,状态码:${status_code}"elseecho "HTTP服务异常,状态码:${status_code}" > "${temp_file}"send_emailfi#!/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#!/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
- 将此脚本保存为
http_monitor.sh
。 - 用你的URL替换
http://example.com
。 - 用你的电子邮件地址替换
youremail@example.com
。 - 赋予脚本执行权限:
chmod +x http_monitor.sh
。 - 执行脚本:
./http_monitor.sh
。
注意:这个脚本会发送警报邮件,需要确保系统已经配置了邮件发送程序(如sendmail、postfix等)。如果需要定时监控,可以将脚本添加到cron定时任务中。
© 版权声明
本站文章由不念博客原创,未经允许严禁转载!
THE END