zabbix自定义监控脚本(统计TCP连接数)
young / / / 阅读量

zabbix自定义监控脚本(统计TCP各状态连接数)
python版本:

# -*- coding: utf-8 -*-
# @Time    : 2018/8/22 20:10
# @Author  : young
# @Email   : young_sc@foxmail.com
# @File    : tcp_status.py
import psutil
import sys
import json
status_list = ["LISTEN", "ESTABLISHED", "TIME_WAIT", "CLOSE_WAIT", "LAST_ACK", "SYN_SENT", "FIN_WAIT2"]
status_temp = []

def TCP(status_list):
    status_name=[]
    for app in status_list:
        if len(app) != 0:
            status_name.append({'{#STATUS_NAME}': app})
    return  json.dumps({'data': status_name}, indent=4, separators=(',', ':'))

def All_connect():
    net_connections = psutil.net_connections()
    for key in net_connections:
        status_temp.append(key.status)


def Status(str):
    count = status_temp.count(str)
    return count


if sys.argv[1] == 'list':
    print(TCP(status_list))
elif sys.argv[1] == 'status':
    All_connect()
    print(Status(sys.argv[2]))

shell版本:

#!/bin/bash
NET=("LISTEN" "ESTABLISHED" "TIME_WAIT" "CLOSE_WAIT" "LAST_ACK" "SYN_SENT" "FIN_WAIT2")
a="$1"
b="$2"
tcp () {
printf '{\n'
printf '\t"data":[\n'
for((i=0;i<${#NET[@]};++i))
{ 
num=$(echo $((${#NET[@]}-1)))
if [ "$i" != ${num} ];
then 
printf "\t\t{ \n" 
printf "\t\t\t\"{#SITENAME}\":\"${NET[$i]}\"\n\t\t},\n"
else 
printf "\t\t{ \n" 
printf "\t\t\t\"{#SITENAME}\":\"${NET[$num]}\"\n\t\t}\n\t]\n}\n"
fi
}
}

LISTEN() {
re=`netstat -tan |grep ^tcp |awk '{++a[$6]} END{for (i in a) print i, a[i]}'|grep "${NET[0]}"| awk '{print $2}' `
if [ -z $re ]
then
re=0
fi
echo "$re"
}

ESTABLISHED() {
re=`netstat -tan |grep ^tcp |awk '{++a[$6]} END{for (i in a) print i, a[i]}'|grep ${NET[1]} |awk '{print $2}'`
if [ -z $re ]
then
re=0
fi
echo "$re"
}
TIME_WAIT() {
re=`netstat -tan |grep ^tcp |awk '{++a[$6]} END{for (i in a) print i, a[i]}'|grep ${NET[2]} |awk '{print $2}'`
if [ -z $re ]
then
re=0
fi
echo "$re"
}
CLOSE_WAIT() {
re=`netstat -tan |grep ^tcp |awk '{++a[$6]} END{for (i in a) print i, a[i]}'|grep ${NET[3]} |awk '{print $2}'`
if [ -z $re ]
then
re=0
fi
echo "$re"
}
LAST_ACK() {
re=`netstat -tan |grep ^tcp |awk '{++a[$6]} END{for (i in a) print i, a[i]}'|grep ${NET[4]} |awk '{print $2}'`
if [ -z $re ]
then
re=0
fi
echo "$re"
}
SYN_SENT() {
re=`netstat -tan |grep ^tcp |awk '{++a[$6]} END{for (i in a) print i, a[i]}'|grep ${NET[5]} |awk '{print $2}'`
if [ -z $re ]
then
re=0
fi
echo "$re"
}
FIN_WAIT2() {
re=`netstat -tan |grep ^tcp |awk '{++a[$6]} END{for (i in a) print i, a[i]}'|grep ${NET[6]} |awk '{print $2}'`
if [ -z $re ]
then
re=0
fi
echo "$re"
}
choice(){
case $b in 
LISTEN)
LISTEN
;;
ESTABLISHED)
ESTABLISHED
;;
TIME_WAIT)
TIME_WAIT
;;
CLOSE_WAIT)
CLOSE_WAIT
;;
LAST_ACK)
LAST_ACK
;;
SYN_SENT)
SYN_SENT
;;
FIN_WAIT2)
FIN_WAIT2
;;
*)
exit
;;
esac
}
case "$a" in
list)
tcp
;;
choice)
choice $b
;;
*)
echo "Usage:$0 {list|choice[stataus]}"
;;
esac
支付宝捐赠
请使用支付宝扫一扫进行捐赠
微信捐赠
请使用微信扫一扫进行赞赏
有 0 篇文章