zabbix自定义监控脚本(统计TCP连接数)

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" "\t\t\t\"{#sitename}\":\"${net[$i]}\"\n\t\t},\n" else "\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}' ` -z $re ] echo "$re" established() ${net[1]} $2}'` time_wait() ${net[2]} close_wait() ${net[3]} last_ack() ${net[4]} syn_sent() ${net[5]} fin_wait2() ${net[6]} choice(){ case $b 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 "$a" list) tcp choice) choice "usage:$0 {list|choice[stataus]}" < pre>