前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >shell | 检测网站存活并自动钉钉告警

shell | 检测网站存活并自动钉钉告警

作者头像
Amadeus
发布2023-12-08 15:22:37
1810
发布2023-12-08 15:22:37
举报
文章被收录于专栏:linux技术linux技术

脚本内容如下, 替换钉钉 bot 的 token, 将脚本放至 crontab 执行即可

代码语言:javascript
复制
#!/bin/bash

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# 设置要检测的网页URL
urls=("https://emp.cnpc.com.cn/index.html" "https://mdm.cnpc.com.cn/")
#urls=("https://emp.cnpc.com.cn/index.html" "https://mdm.cnpc.com.cn/" "https://www.956100.com" "https://mm.956100.com" "https://app.956100.com")

# 钉钉机器人的 webhook 地址
webhook="https://oapi.dingtalk.com/robot/send?access_token=******************************"

# 最大连续无法访问次数
max_attempts=3

# 设置并发进程数为 URL 数量
max_concurrent=${#urls[@]}

# 初始化计数器
completed=0

for url in "${urls[@]}"; do
    # 在后台启动一个子进程进行测试
    (
        attempts=0
        while [ $attempts -lt $max_attempts ]; do
            # 使用curl获取网页内容,并保存HTTP状态码到变量response_code
            response_code=$(curl -s --connect-timeout 5  -o /dev/null -w "%{http_code}" "$url")

            # 判断HTTP状态码来确定网页是否可访问
            if [ "$response_code" -eq 200 ]; then
                break
            else
                attempts=$((attempts + 1))
            fi

            if [ $attempts -ge $max_attempts ]; then
                message="告警: $(date +"%Y年%m月%d日-%H:%M:%S") ${url} 网页无法访问,HTTP状态码: $response_code"
                curl -X POST ${webhook} -H "Content-Type: application/json" -d "{\"msgtype\": \"text\", \"text\": {\"content\":\"$message\"}}"
                break
            fi

            sleep 60  # 等待 20 秒后再次尝试
        done

            completed=$((completed + 1))
    ) &

    # 控制并发进程数
    if [ $completed -ge $max_concurrent ]; then
        wait
        completed=0
    fi
done

# 等待剩余的并发进程完成
wait

exit 0
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-12-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档