原創:用zabbix api批量添加web監控

代碼如下,進攻大家參考,轉載的話說明來源

前面5個變量自行補齊,

 

#!/usr/local/python3.51/bin/python3
# Author:         Anxinhai@wondersgroup
# Mail:           [email protected]
from pyzabbix import ZabbixAPI
import sys
from re import compile,IGNORECASE
ZABBIX_SERVER = ""
USER = ""
PASSWORD = ""
HOSTNAME = "" 
URL=""
def login(ZABBIX_SERVER,USER,PASSWORD):
  zapi = ZabbixAPI(ZABBIX_SERVER)
  zapi.login(USER,PASSWORD)
  return zapi
def gethostid(auth,HOSTNAME):
  request = ZabbixAPI.do_request(auth, 'host.get', params={ "filter": {"host":HOSTNAME}})
  if request['result']:
    return request['result'][0]['hostid']
  else:
    print ("找不到該主機")
    sys.exit(1)
def getapplicationid(auth,hostid):
  try:
    request = ZabbixAPI.do_request(auth, 'application.create', params={"name": "web監控","hostid": hostid})
  except Exception as e:
    print(e)
  request = ZabbixAPI.do_request(auth, 'application.get', params={"hostids": hostid})
  for num in range(0,len (request['result'])):
    if request['result'][num]['name'] == "web監控":
      return request['result'][num]['applicationid']
def create_web_scenario(auth,URL,hostid,applicationid):
  request = ZabbixAPI.do_request(auth, 'httptest.get', params={ "filter": {"name": URL}})
  if request['result']:
    print('該web監控已經添加過了' )
  else:
    try:
      ZabbixAPI.do_request(auth, 'httptest.create',params={"name": URL,"hostid": hostid,"applicationid": applicationid, "delay": '60',"retries": '3', "steps": [ { 'name': URL, 'url': URL, 'no': '1'} ] } )
    except Exception as e:
      print(e)
def create_trigger(auth,HOSTNAME,URL):
  expression="{"+"{0}:web.test.fail[{1}].last()".format(HOSTNAME,URL)+"}"+"<>0"
  try:
    ZabbixAPI.do_request(auth, 'trigger.create', params={"description": "從監控機(172.18.11.34)訪問{0}出現問題,如果網絡和主機性能沒問題,並且是單節點報錯請嘗試重啓對應的tomcat".format(URL),"expression": expression,"priority":5})  
  except Exception as e:
    print(e)

auth = login(ZABBIX_SERVER,USER,PASSWORD)
hostid = gethostid(auth,HOSTNAME)
applicationid=getapplicationid(auth,hostid)
create_web_scenario(auth,URL,hostid,applicationid)
create_trigger(auth,HOSTNAME,URL)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章