文件 /etc/zabbix/zabbix_agentd.d/userparameter_ww.conf 添加一行

UserParameter=ww.tcpportlisten,python /etc/zabbix/check_listenport.py

visudo添加一行

# visudo
zabbix ALL=(root) NOPASSWD:/bin/netstat

创建脚本文件

$ cat /etc/zabbix/check_listenport.py

#!/usr/bin/env python
# -*- coding: utf8 -*-
# author: ww
# purpose: For Get The Listening Service PORT
# Date: 2015-12-01

from subprocess import Popen, PIPE
from re import compile
import json

if __name__ == "__main__":

alllist = []
data = {}

# 这里添加需要监控的服务名称, 默认只有sshd
slist = [
# 'sshd', 'vsftpd',
'memcached', 'dnsmasq',
'nginx','mongod','mysqld',
# 'java',
'qpidd','redis-s','php-fpm'
]

objlist = map(compile, slist)

content = Popen("sudo netstat -ntlp|grep 'LISTEN'", shell=True, stdout=PIPE, stderr=PIPE)
cmdout = content.communicate()

commandline = cmdout[0].split('\n')

for _, item in enumerate(commandline):
for _, obj in enumerate(objlist):
snamelist = obj.findall(item)
if len(snamelist) == 1:
tmpdic = {}
try:
port = str(item.split()[3].split(':')[-1])
except Exception,e:
continue

tmpdic["{#SERVICEPORT}"] = port
tmpdic["{#SERVICENAME}"] = snamelist[0]
alllist.append(tmpdic)

f = lambda x,y: x if y in x else x + [y]
alllist = reduce(f, [[], ] + alllist)

data['data'] = alllist
jsonStr = json.dumps(data, sort_keys=True, indent=4)
print jsonStr

最后更新: 2018年10月18日 16:48

原始链接: http://cwiwi.com/2018/10/18/zabbix-listen-port-scriptv1/