https://www.cnblogs.com/goldd/p/5761243.html

https://blog.51cto.com/9429042/2318210   这个和书上几乎一样

python实现zabbix_sender的socket通信代码样例

sk = socket.socket()
sk.connect(self.ip_port)
sk.settimeout(5)
sk.sendall(b’ZBXD\x01′)
sk.sendall(b’Q\x00\x00\x00\x00\x00\x00\x00′)
sk.sendall(b'{“request”:”sender data”,”data”:[{“host”:”127.0.0.1″,”key”:”abc”,”value”:”123″}]}’)
try:
a = sk.recv(1024).decode(‘ascii’)
except:
return 0
else:
return 1

第二个网址的代码

#!/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()

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注