#!/usr/bin/python #--*-- coding: utf-8 --*-- ##Python 2.6.9 ##Zabbix Server 3.4 import socket import struct import os import json import time class ZabbixSender: def __init__(self,server_host,server_port=10051): self.server_ip = server_host self.server_port = server_port self.zbx_header = 'ZBXD' self.zbx_sender_data = {u'request':u'sender data',u'data':[]} self.zbx_version = 1 send_data = '' def AddData(self,host,key,value,clock=None): add_data = {u"host":host,u'key':key,u'value':value} if clock != None: add_data[u'clock'] = clock self.zbx_sender_data['data'].append(add_data) return self.zbx_sender_data def ClearData(self): self.zbx_sender_data['data'] = [] return self.zbx_sender_data def __MakeSendData(self): zbx_sender_json = json.dumps(self.zbx_sender_data,separators=(',',':'),ensure_ascii=False).encode('utf-8') json_byte = len(zbx_sender_json) self.send_data = struct.pack("<4sBq" + str(json_byte) + "s",self.zbx_header,self.zbx_version,json_byte,zbx_sender_json) def Send(self): self.__MakeSendData() so = socket.socket() so.connect((self.server_ip,self.server_port)) wobj = so.makefile(u'wb') wobj.write(self.send_data) wobj.close() robj = so.makefile(u'rb') recv_data = robj.read() robj.close() so.close() tmp_data = struct.unpack("<4sBq" + str(len(recv_data) - struct.calcsize("<4sBq")) + "s",recv_data) recv_json = json.loads(tmp_data[3]) return recv_json ##9.38.91.200::zabbix server address sender = ZabbixSender(u"9.38.91.200") ###獲取被監控主機上的指定IP的TCP鏈接數,監控其餘項時可本身實現對應的參數獲取方法 sys_tcp_conns_hdc = os.popen("netstat -antp | grep 8183 | grep 99.38.21.13 | wc -l").read() ###發送監控的key到zabbix server以前,必須在zabbix server上配置trigger類型的監控項,配置監控主機的時候主機名必定要和此處上傳的主機名一致(都是cna1),監控項爲test和hdc-tcp-conns,這兩項必需要在zabbix server上先配置爲trigger類型的item,zabbix server纔會接收數據。 sender.AddData(u'cna1',u'test',u'send test data') sender.AddData(u'cna1',u'hdc-tcp-conns',sys_tcp_conns_hdc) res = sender.Send()