监控业务应用端口通过钉钉报警

1 钉钉提示信息

业务告警
主机ip:x.x.x.x
主机名称:test
端口:2001 port is not running
服务名称:ability-sms-core

2 思路准备

获取本地tcp所有端口

port1=netstat -an|grep LISTEN|egrep "0.0.0.0|:::"|awk '/^tcp/ {print $4}'|awk -F: '{print $2}'|sort -n

获取pid和进程名

lsof -n -i:9001|grep TCP|grep LISTEN|grep IPv4|awk '{printf("%d\t%s\n"),$2,$1}'

3 编写脚本

vim ports_check.sh

#!/bin/bash
#chkconfig:2345 81 91
#decription:ports_check autostart
declare -A PORTS_SERVICE
PORTS=(2001 22 6001 6002 6003 6004 6005 6006 6007 6008 6009 9001 9002 9003)
PORTS_SERVICE=([2001]="ability-sms-core" [22]="sshd" [6001]="biz-app-core" [6002]="biz-user-core" [6003]="biz-feed-core" [6004]="bm-pms" [6005]="bm-biz" [6006]="biz-im-core" [6007]="biz-feed-post" [6008]="biz-job" [6009]="biz-points-core" [9001]="api-gateway" [9002]="fun-uaa" [9003]="bm-gateway")
HOST=`curl ip.sb`
HOSTNAME=`echo $(hostname)`
function SendMessageToDingding(){
        url="https://oapi.dingtalk.com/robot/send?access_token=xxxx"
        UA="Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
 
        res=`curl -XPOST -s -L -H "Content-Type:application/json" -H "charset:utf-8" $url -d "
        {
        \"msgtype\": \"text\",
        \"text\": {
                 \"content\": \"业务告警\n主机ip:$1\n主机名称:$2\n端口:$3 port is not running\n服务名称:$4\"
                 }
    }"`
 
        echo $res
}
#也可以写成for i in ${array[@]}
for i in ${PORTS[*]}
do
   #echo "主机为$HOST,端口为$i"
   port_num=`netstat -lntup|grep -w $i|wc -l`
   service_name=`echo ${PORTS_SERVICE[$i]}`
   #echo "端口为$i,数量为$port_num"
    if [ $port_num -eq 0 ];then
         port_current=$i
         #钉钉报警地址
       SendMessageToDingding $HOST  $HOSTNAME $port_current $service_name
       echo "$(date "+%Y-%m-%d %H:%M:%S"):主机$HOST的端口$port_current  is not running,服务名称:$service_name" >> /root/ports_check.log
       #else
       #echo "$(date "+%Y-%m-%d %H:%M:%S"):主机$HOST的端口$i  is running,服务名称:$service_name" >> /root/ports_check.log
    fi
done

4 添加开机启动

chmod +x ports_check.sh
ln -s /root/ports_check.sh /etc/rc.d/init.d/ports_check
chkconfig --add ports_check
chkconfig  ports_check on
chkconfig --list

5 添加定时任务

crontab -e
*/5 * * * * /bin/sh /etc/rc.d/init.d/ports_check >/dev/null 2>&1

 

你可能感兴趣的:(脚本,监控)