• UDP端口检查告警SHELL脚本(企业微信版机器人版)


    脚本准备

    • 0Batch_Check.sh
    • 1port_check.sh
    • 2wechat_bot_alert.sh
    • CheckList

    CheckList

    #支持大/小写
    10.1.1.5 Udp 53
    127.0.0.1 Tcp 1234
    

    0Batch_Check.sh

    #!/bin/sh
    while read LineX
    do
    	#echo $LineX
    	./1port_check.sh $LineX
    done < ./CheckList
    

    1port_check.sh

    #!/bin/sh
    #TCP UDP port check and alert
    #useage: port_check.sh  IP  PROTOCOL  PORT
    
    input_IP=$1
    input_PROTOCOL=$2
    input_PORT=$3
    
    #将大小写转成临时小写
    tmp_PROTOCOL=`echo ${input_PROTOCOL} | tr '[A-Z]' '[a-z]'`
    #echo $tmp_PROTOCOL
    
    if [[ "${tmp_PROTOCOL}" == "tcp" ]]; then
        abbreviate_PROTOCOL="S"
    elif [[ "${tmp_PROTOCOL}" == "udp" ]]; then
        abbreviate_PROTOCOL="U"
    else
        echo "Unknown PROTOCOL" && exit 1
    fi
    
    /usr/bin/nmap ${input_IP} -s ${abbreviate_PROTOCOL} -p ${input_PORT} |grep "$input_PORT/$tmp_PROTOCOL open" &>/dev/null
    if [[ $? == 0 ]]
    then
    	echo "${input_IP} ${tmp_PROTOCOL} Port ${input_PORT} Check OK"
    else
    	#A调用自建告警应用
    	## ./2wechat_app_alert.py 5 "WarningIP: ${input_IP}" "DES: ${tmp_PROTOCOL} Port ${input_PORT} is DOWN!"
    	#B调用群机器人
    	./2wechat_bot_alert.sh  "Warning!!!  ${input_IP} : ${tmp_PROTOCOL} Port ${input_PORT} is DOWN!"
    fi
    

    2wechat_bot_alert.sh

    #!/bin/sh
    #useage: bot_alert.sh a b c ...
    
    /usr/bin/curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxxxxx' 
    -H 'Content-Type: application/json' 
       -d '
       {
            "msgtype": "text",
            "text": {
                "content": "'$*'",
                "mentioned_list":["ZhangSan","LaoLiu"]
            }
       }'
    

    加到定时任务中

    crontab -l

    */10 * * * * cd /data/Script/ && ./0Batch_Check.sh &>/dev/null

    参考资料

    学了一招:在json格式中引用shell变量的技巧,实际上是把 -d 后面的data分为了三个部分:
    '{"msgtype...content": "' 加上 $* 再加上 '","mentioned_...}' 。
    感谢博主:https://jaminzhang.github.io/shell/the-problem-of-curl-commit-json-data-include-shell-variables/

    企业微信群机器人手册:https://work.weixin.qq.com/api/doc/90000/90136/91770

    ================# 水平有限 欢迎留言 批评指正 #=================
  • 相关阅读:
    Oracle与MySQL的几点区别
    MySQL使用Union创建视图报错
    MySQL指定mysqld启动时所加载的配置文件
    MySQL使用位运算
    django rest framework(3)
    Django Rest Framework(2)
    Django 之缓存
    RESTful API
    restful framework 认证源码流程
    其他排序
  • 原文地址:https://www.cnblogs.com/max27149/p/12206600.html
Copyright © 2020-2023  润新知