最近要部署smokeping,想使用nginx的fastcgi的方式来部署,结果perl的执行的效率真是大失所望,就想用zabbix来实现smokeping。


python 环境2.6

参考的zabbix 社区

https://www.zabbix.com/forum/showthread.php?t=31147


实现的原理使用zabbix_sender主动向zabbixserver发送数据,zabbix就能采集到数据啦

文件清单:

     all  create_graph.py  create_other_screen.py  define monitor.py  zbxsmokepingprimary        zbx_export_templates.xml


文件说明: 

    all: 所要监控ip地址池,这个文件monitor.pycreate_graph.py都会在这里读取ipcreate_graph.py是个多线程的脚本用于发送all的所有ipzabbixservermonitor.py去读取all文件的ip生成所需要监控的主

    define: 定义客户的ip地址,这个文件会被create_create_other.py读取,create_other_screen.py实现读取define文件中的ip地址实现自动生成带客户screen,手动生成的话会该觉很头痛

   zbxsmokepingprimary: 是外部的执行的脚本需要在zabbix_server设置

   zbx_export_templates.xml 模版文件

 

 

设置的选项:

      zabbix_server

                       开启这个选项ExternalScripts=/usr/local/share/zabbix/externalscripts

     zbxsmokepingprimary

                       ZBXSERVERzabbix服务器的ip地址

                       FPINGfping的位置

                       ZBXSENDERzabbix_sender的位置

            zabbix主机监控有个类型为external check 选项会去执行 zbxsmokepingprimary这个脚本,这个脚本需要有执行的权限

 

     monitor.pycreate_other_screen.py需要修改的zabbix url地址,帐号和密码 

   create_graph.py:

         num_threads=10 设置初始化的线程个数,ip多的话初始线程可以跟ip个数相等

软件包:

     supervisorpython的程序,监控脚本,使之一直运行,supervisor需要执行的文件为create_graph.py,这个就相当于守护进程来使用

     pyzabbixpython连接zabbixapi


monitor.py 代码:

#!/usr/bin/env python

import pyzabbix


class zabbix(object):
	def __init__(self):
		self.all=open('all')

	def _login(self):
		zapi= pyzabbix.ZabbixAPI('url')  #your zabbix url
		zapi.login('user','password') # you zabbix user and password the user have write privilege
		return zapi

	def _get_template(self):
		temp=self._login().template.get(output='extend',filter={'host':'Template_SmokePrimary'})
		return  temp[0]['templateid']
	
	def _get_group(self):
		if  not self._login().hostgroup.exists(name='ping_check'):
			
			self._login().hostgroup.create(name='ping_check')
		group=self._login().hostgroup.get(output='extend',filter={'name':'ping_check'})
		return group[0]['groupid']

	def _create_host(self):
		for x in self.all:
			if not self._login().host.exists(host=x.strip()):
				try:
					self._login().host.create(
								host=x.strip(),
								interfaces={"type":1, "main":1, "useip":1, "ip":"127.0.0.1","dns":"","port":"10050"},
								groups={"groupid":str(self._get_group())},
								templates={"templateid":str(self._get_template())},
								)
				except Exception,e:
					print e
			
				
	

	def main(self):
#		self._get_group()
#		self._get_template()
		self._create_host()

if __name__ == '__main__':
	a=zabbix()
	a.main()	



create_other_screen.py代码:

#!/usr/bin/env python

import pyzabbix
import re

class zabbix(object):
        def __init__(self):
                self.define=open('define')
		self.dynamic=0
		self.columns=2
		for x in self.define:
			self.name=x.strip()
			break         #the first line is you screen's name

        def _login(self):
                zapi= pyzabbix.ZabbixAPI('url') #you zabbix server url
                zapi.login('admin','zabbix')  #your zabbix user and password
                return zapi
	
	def _get_host(self):
		host_ids=[]
		for x in self.define:
			if not re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',x.strip()):
				continue
			if self._login().host.exists(host=x.strip()):
				hosts=self._login().host.get(filter={'host':[x.strip()]})
				host_ids.append(hosts[0]['hostid'])
		return  host_ids

	def _get_graph(self):
		graph_ids=[]
		for x in self._get_host():
			graph=self._login().graph.get(hostids=x)
			graph_ids.append(graph[0]['graphid'])

		graph_list=[]
		x = 0
		y = 0		
		for graph in sorted(graph_ids):
                        graph_list.append({
                                        "resourcetype":'0',
                                        "resourceid": graph,
                                        "width": "600",
                                        "height": "100",
                                        "x": str(x),
                                        "y": str(y),
                                        "colspan": "0",
                                        "rowspan": "0",
                                        "elements": "0",
                                        "valign": "0",
                                        "halign": "0",
                                        "style": "0",
                                        "url": "",
                                        "dynamic": str(self.dynamic)
                                        })
                        x += 1
                        if x == int(self.columns):
                                x = 0
                                y += 1		
		return  graph_list	
	
	def _get_screen(self):
		id=self._login().screen.get(output='extend',filter={'name':self.name})
		return id[0]['screenid']	
	def _create_screen(self): 
		if self._login().screen.exists(name=self.name):
			self._login().screen.delete(str(self._get_screen()))
			#return 0
                graphids=self._get_graph()
                columns = int(self.columns)
                if len(graphids) % self.columns == 0:
                        vsize = len(graphids) / self.columns
                else:
                        vsize = (len(graphids) / self.columns) + 1
                self._login().screen.create(name=self.name,hsize=self.columns,vsize=vsize,screenitems=graphids)	

	def main(self):
#		self._get_graph()
#		self._get_screen()
		self._create_screen()

if __name__ == '__main__':
	a=zabbix()
	a.main()



create_graph.py 代码

#!/usr/bin/env python

import subprocess
from threading import Thread
from  Queue import Queue
import time

f=open('all')
d=[]
for x in f:
	d.append('/usr/local/share/zabbix/externalscripts/zbxsmokepingprimary  %s 10 1000 32 %s' % (x.strip(),x.strip()))

queue=Queue()
def do(i,q):
	while True:
		a=q.get()
		ret=subprocess.call(a,shell=True)

		q.task_done()

num_threads=10  #init thread number

for i in range(num_threads):
	worker = Thread(target=do,args=(i,queue))
	worker.setDaemon(True)
	worker.start()
		
	
for x in d:
	queue.put(x)

queue.join()

time.sleep(3)

我这边对于主机在screen中没有排序,每个人的需求可能不同

下面附上脚本文件,软件包需要自己去下载。。。。。


下面是我在百度和163域名解析到的ip地址生成的图片

wKiom1N_CUrzeDy7AAQqY2RWtOo255.jpg