zabbix自動停用與開啓agent

咱們在升級環境時遇到了一個問題,那就是zabbix會自動發送郵件給領導,此時領導內心會嘎嘣一下,爲了給領導營造一個良好的環境,減小沒必要要的告警郵件,減小嘎嘣次數,因而在升級以前,取消zabbix監控的agent,當升級完以後再恢復過去。php


 

1、簡介

zabbix提供了API接口,可知足基本使用需求,具體參考:zabbix API前端

有了API接口,咱們就能夠作到:python

  自動執行常規任務web

  將zabbix與第三方軟件集成json

   建立新的應用程序以使用zabbixubuntu

zabbix API 是基於web API的,使用的是JSON-RPC2.0協議,客戶端與API之間的請求使用的是JSON格式進行編碼。api

使用遠程http請求調用api,須要向 api_jsonrpc.php 位於前端目錄中的文件發送HTTP POST請求,url是http://zabbixserverIP/zabbix/api_jsonrpc.php。app

 請求的頭部信息 必須是如下值之一:函數

application/json-rpc, application/json 或 application/jsonrequest

json中主要的對象有:工具

jsonrpc - API使用的JSON-RPC協議的版本; Zabbix API實現的JSON-RPC版本是2.0;
method - 被調用的API方法名;
params - 將被傳遞給API方法的參數;
id - 請求的任意標識符;
auth -用戶認證令牌; 由於咱們尚未一個,它的設置null。

  

2、思路整理

  登錄zabbix,獲取token

  利用token獲取agent的id

  利用已獲取的id和token調整agent的鏈接狀態

 

3、具體實現

 

#!/usr/bin/python
import sys import json import requests if( len(sys.argv) < 2 ):    #需強調傳入3個以上的參數 print("[Usage] $1 is 0/1(0:open 1:off) ; $2 $3.... is agent name. ") sys.exit(1) class Error(Exception):    #定義自定義錯誤 def __init__(self,*args): self.args = args def login(user,passwd,url,header):  #登錄函數獲取token # return token data = { "jsonrpc": "2.0" , "method": "user.login" ,     "params": { "user": user , "password": passwd } , "id": 1 , } r = requests.post ( url=url , headers=header , data=json.dumps ( data ) ) if ( r.status_code == 200 ): return r.json ()['result'] else: raise Error("return status code is not eq 200. login failed!") def gethostid(hostname,token,url,header):  #獲取id #get dict { hostid , status} data = { "jsonrpc": "2.0" , "method": "host.get" , "params": { "output": ['status'] , "filter": { "host": [ hostname ] } } , "auth": token , "id": 1 } r = requests.post ( url=url , headers=header , data=json.dumps ( data ) ) if( r.status_code == 200 ): if( r.json()['result'] != [] ):   #判斷獲取到的信息不爲「[]」證實是有數據的 return r.json ()['result'][0] else: print(" %s hostname is wrong!!" % hostname) exit(1) else: raise Error("return status code is not eq 200. gethostid failed!") def changestatus(hostid,token,url,header,onoroff):   #修改agent的鏈接狀態 # 0:open ; 1:off data = { "jsonrpc": "2.0" , "method": "host.update" , "params": { "hostid": hostid , "status": onoroff } , "auth": token , "id": 1 } r = requests.post ( url=url , headers=header , data=json.dumps ( data ) ) r.close() if ( r.status_code == 200 ): return r.json ()['result']["hostids"] else: raise Error("return status code is not eq 200. changestatus failed!") if __name__ == '__main__': allhostname = [ i for i in sys.argv[2:]] onoroff = int(sys.argv[1]) #allhostname = ["agent1","agent2"] #onoroff = 0 msg = {0:"on",1:"off"}  #設定開關,0爲開啓,1爲關閉 url = 'http://zabbixserverip/zabbix/api_jsonrpc.php'    #後綴必須是 zabbix/api_jsonrpc.php user = 'bill' passwd = '123456' header = {"Content-Type": "application/json"} try: for hostname in allhostname: token = login ( user , passwd , url , header ) dict = gethostid(hostname,token,url,header) print(dict) hostid = dict["hostid"] status = dict["status"] print("defore the change,hostname: %s hostid:%s status:%s [ %s ] " % (hostname,hostid,status,msg[onoroff])) if( onoroff != int(status)):     res=changestatus(hostid,token,url,header,onoroff) dict2 = gethostid ( hostname , token , url , header ) hostid2 = dict2["hostid"] status2 = dict2["status"] print("after the change status: %s [ %s ]" % (status2,msg[onoroff]) ) if (status != status2 ): print(" %s [ %s ] successful!" % (hostname,msg[onoroff])) else: print(" %s [ %s ] failed!" % (hostname , msg[onoroff]) ) else: print("current %s is %s ,No change." % (hostname,msg[onoroff])) except Exception as e: print(e)

  將文件移動到ubuntu上,文件名是zabbixagent_onoff.py,能夠跟多個主機名,主機名host name,不是visible name

 

 再將其加入jenkins等持續集成工具中,就可實現開關agent了

相關文章
相關標籤/搜索