• 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

    ================# 水平有限 欢迎留言 批评指正 #=================
  • 相关阅读:
    PHP正则表达式
    结构体
    golang 基础笔记一
    Goland常用快捷键
    接口和断言
    golang 案例分析
    Gun make可识别指示符
    makefile中SHELL变量的设置
    蓝牙耳机声音太大、太小调节
    查看SecureCRT会话中保存的密文
  • 原文地址:https://www.cnblogs.com/max27149/p/12206600.html
Copyright © 2020-2023  润新知