python3 端口发现

  1. #!/bin/env python3
  2. import subprocess
  3. import json
  4. import re
  5. def PortList():
  6. CMD = "sudo netstat -pntl | awk '{print $4,$7}'|grep [0-9] |egrep -vw '%s'"
  7. Result_str = subprocess.getoutput(CMD)
  8. #print(Result_str)
  9. tmp_list = Result_str.split("\n")
  10. #print(tmp_list)
  11. port_dict = {}
  12. for line in tmp_list:
  13. # print(line)
  14. PORT_REG = re.search(r"(127.0.0.1:|:::|0.0.0.0:)(\d+).+\d+/(\S+)",line)
  15. # print(PORT_REG)
  16. if PORT_REG is not None:
  17. match_line = (PORT_REG.groups())
  18. port_dict [ match_line[1]] = match_line[2]
  19. return port_dict
  20. if __name__ == "__main__":
  21. Results = PortList()
  22. ports = []
  23. for key in Results:
  24. ports += [{'{#PNAME}':key,'{#PPORT}':Results[key]}]
  25. print(json.dumps({'data':ports},sort_keys=True,indent=4,separators=(',',':')))
  26. 以上脚本功能实现。然后在zabbix_agentd.d中添加key,以及调用脚本功能目录。
  27. UserParameter=discovery.ports,/usr/bin/python /usr/lib/zabbix/externalscripts/zabbix_ports_discovery.py

添加模版

zabbix 端口发现监控 - 图1

配置自动发现规则

zabbix 端口发现监控 - 图2

配置监控原型

zabbix 端口发现监控 - 图3

配置触发器

zabbix 端口发现监控 - 图4

主机关联模版

zabbix 端口发现监控 - 图5

python2

#!/usr/bin/python
# -*- coding: utf-8 -*-
# 使用python2 commands模块

import re
import commands
import json

DROP_LIST = ['22','25','111']    # 排除端口

def filterList():
    DROP_str = "|".join(DROP_LIST)
    CMD="sudo netstat -pntl | awk '{print $4,$7}'|grep  [0-9] |egrep -vw '%s'" % (DROP_str)
    Result_Str = commands.getoutput(CMD)
    #print (Result_Str)
    tmp_list = Result_Str.split("\n") #每行加入列表
    new_dict = {}
    for line in tmp_list:
       # print (line)
       PORT_REG = re.search(r"(127.0.0.1:|:::|0.0.0.0:)(\d+).+\d+/(\S+)",line)
       if PORT_REG is not None:
           match_line =  (PORT_REG.groups())
           new_dict[ match_line[-1]]  =  match_line[-2]
    return new_dict

if __name__ == "__main__":
    Results = filterList()

    #格式化成适合zabbix lld的json数据
    ports = []
    for key  in  Results:
        ports += [{'{#PNAME}':key,'{#PPORT}':Results[key]}]
    print json.dumps({'data':ports},sort_keys=True,indent=4,separators=(',',':'))