最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python從ZabbixAPI獲取信息及實現(xiàn)Zabbix-API 監(jiān)控的方法

 更新時間:2018年09月17日 08:34:38   投稿:mrr  
這篇文章主要介紹了Python從ZabbixAPI獲取信息及實現(xiàn)Zabbix-API 監(jiān)控的方法,需要的朋友可以參考下

Python編寫從ZabbixAPI獲取信息

此腳本用Python3.6執(zhí)行是OK的。
# -*- coding: utf-8 -*-
import json
import urllib.request, urllib.error, urllib.parse
class ZabbixAPI:
 def __init__(self):
  self.__url = 'http://192.168.56.102/zabbix/api_jsonrpc.php'
  self.__user = 'admin'
  self.__password = 'zabbix'
  self.__header = {"Content-Type": "application/json-rpc"}
  self.__token_id = self.UserLogin()
 #登陸獲取token
 def UserLogin(self):
  data = {
   "jsonrpc": "2.0",
   "method": "user.login",
   "params": {
    "user": self.__user,
    "password": self.__password
   },
   "id": 0,
  }
  return self.PostRequest(data)
 #推送請求
 def PostRequest(self, data):
  request = urllib.request.Request(self.__url,json.dumps(data).encode('utf-8'),self.__header)
  result = urllib.request.urlopen(request)
  response = json.loads(result.read().decode('utf-8'))
  try:
   # print response['result']
   return response['result']
  except KeyError:
   raise KeyError
 #主機列表
 def HostGet(self,hostid=None,hostip=None):
  data = {
   "jsonrpc":"2.0",
   "method":"host.get",
   "params":{
    "output":"extend",
    "selectGroups": "extend",
    "selectParentTemplates": ["templateid","name"],
    "selectInterfaces": ["interfaceid","ip"],
    "selectInventory": ["os"],
    "selectItems":["itemid","name"],
    "selectGraphs":["graphid","name"],
    "selectApplications":["applicationid","name"],
    "selectTriggers":["triggerid","name"],
    "selectScreens":["screenid","name"]
   },
   "auth": self.__token_id,
   "id":1,
  }
  if hostid:
   data["params"]={
    "output": "extend",
    "hostids": hostid,
    "sortfield": "name"
   }
  return self.PostRequest(data)
 #主機列表
 def HostCreate(self,hostname,hostip,groupid=None,templateid=None):
  data = {
   "jsonrpc":"2.0",
   "method":"host.create",
   "params": {
    "host": hostname,
    "interfaces": [
     {
      "type": 1,
      "main": 1,
      "useip": 1,
      "ip": hostip,
      "dns": "",
      "port": "10050"
     }
    ],
    "groups": [
     {
      "groupid": groupid
     }
    ],
    "templates": [
     {
      "templateid": templateid
     }
    ]
   },
   "auth": self.__token_id,
   "id":1,
  }
  return self.PostRequest(data)
 #主機組列表
 def HostGroupGet(self,hostid=None,itemid=None):
  data = {
   "jsonrpc":"2.0",
   "method":"hostgroup.get",
   "params":{
    "output": "extend",
    "hostids": hostid,
    "itemids": itemid,
    "sortfield": "name"
   },
   "auth": self.__token_id,
   "id":1,
  }
  return self.PostRequest(data)
 #監(jiān)控項列表
 def ItemGet(self,hostid=None,itemid=None):
  data = {
   "jsonrpc":"2.0",
   "method": "item.get",
   "params": {
    "output": "extend",
    "hostids": hostid,
    "itemids": itemid,
    "sortfield": "name"
   },
   "auth": self.__token_id,
   "id":1,
  }
  return self.PostRequest(data)
 #模板列表
 def TemplateGet(self, hostid=None,templateid=None):
  data = {
   "jsonrpc":"2.0",
   "method": "template.get",
   "params": {
    "output": "extend",
    "hostids": hostid,
    "templateids": templateid,
    "sortfield": "name"
   },
   "auth": self.__token_id,
   "id":1,
  }
  return self.PostRequest(data)
 #圖像列表
 def GraphGet(self,hostid=None,graphid=None):
  data = {
   "jsonrpc":"2.0",
   "method": "graph.get",
   "params": {
    "output": "extend",
    "hostids": hostid,
    "graphids": graphid,
    "sortfield": "name"
   },
   "auth": self.__token_id,
   "id":1,
  }
  return self.PostRequest(data)
 #歷史數(shù)據(jù)
 def History(self,itemid,data_type):
  data = {
   "jsonrpc": "2.0",
   "method": "history.get",
   "params": {
    "output": "extend",
    "history": data_type,
    "itemids": itemid,
    "sortfield": "clock",
    "sortorder": "DESC",
    "limit": 30
   },
   "auth": self.__token_id,
   "id": 2
  }
  return self.PostRequest(data)
#測試:python manager.py shell ; from ZABBIX.ZabbixAPI import * ; main(),代碼修改了要ctrl+Z退出重進
def main():
 zapi=ZabbixAPI()
 token=zapi.UserLogin()
 print(token)
 #39378ec03aa101c2b17d1d2bd6f4ef16
 hosts=zapi.HostGet()
 print(hosts)
 #[{u'host': u'Zabbix server', u'hostid': u'10084', u'interfaces': [{u'interfaceid': u'1', u'ip': u'127.0.0.1'}]}]
if __name__ == '__main__':
 main()

下面看下使用python實現(xiàn) Zabbix-API 監(jiān)控的方法

做運維的朋友應(yīng)該知道,公司IDC機房經(jīng)常有上架、下架、報修和報廢的服務(wù)器。如果服務(wù)器數(shù)量很多的時候很容易造成監(jiān)控遺漏。

       大的互聯(lián)網(wǎng)公司把監(jiān)控系統(tǒng)和CMDB(資產(chǎn)管理系統(tǒng)|配置管理數(shù)據(jù)庫系統(tǒng))集成在一起,當(dāng)上架一臺新機器的時候CMDB里面會記錄相關(guān)的信息,Zabbix根據(jù)CMDB里面信息自動Link相關(guān)的模塊,添加|刪除監(jiān)控。很多小的公司沒有資產(chǎn)管理系統(tǒng),但作為監(jiān)控的負(fù)責(zé)人應(yīng)該每天知道上架了哪些新的機器,確保能添加到Zabbix監(jiān)控里面。
      首先給大家說一下腳本思路:

1)通過Nmap工具掃描網(wǎng)段,掃描出已經(jīng)使用的IP地址。
2)通過Nmap檢測已經(jīng)掃描IP的3389或者22端口是否開放,可以判斷那些事windows機器,那些是Linux機器。
3)Linux下面通過ssh + hostname命令找出Linux主機名。
4)Windows下面通過nmblookup -A 命令找出Windows主機名。
5)用Python腳本讀掃描結(jié)果文件,把主機名寫到列表里面。
6)用Zabbix python API 調(diào)用已經(jīng)監(jiān)控的主機名,寫到列表里面。
7)兩個列表取交集,用for循環(huán)判斷哪些主機名沒有監(jiān)控。
8)發(fā)郵件通知監(jiān)控負(fù)責(zé)人。

    下面我分享一下我寫的Python寫的腳本,其中scan_machine.sh是我調(diào)用的用Shell寫的關(guān)于Nmap掃描的腳本,scan_hostname.log是Nmap掃描的結(jié)果,里面內(nèi)容是IP 主機名。

#!/usr/bin/env python#create by:sfzhang 20140820#coding=utf-8import os,sysimport jsonimport urllib2import datetime,timefrom urllib2 import URLError
nmap_cmd = "/shell/machine/scan_machine.sh"def runCmd(command):
 global mail_cmd
 mail_cmd = '''mail -s "Report on not monitor Hosts of Zabbix" shifeng_zhang88 < /shell/machine/result/result.txt'''
 return os.system(command)runCmd(nmap_cmd)def nmap_host():
 hostiplst = []
 hostnamelst = []
 f = file('/shell/machine/result/scan_hostname.log')
 for line in f.readlines():
 hostip = line.split()[0]
 hostname = line.split()[1]
 hostiplst.append(hostip)
 hostnamelst.append(hostname)
 hostnamelst.sort()
 #print hostiplst
 return hostnamelst
 f.close()def zabbix_host():
 zabbixhostlst= []
 #based url and required header
 url = "http://192.168.161.128/api_jsonrpc.php"
 header = {"Content-Type": "application/json"}
 #request json
 data = json.dumps(
 { 
 "jsonrpc": "2.0",
 "method": "host.get",
 "params":{
  "output":["hostid","name"],
  "filter":{"host":""}
 }, 
 #auth id
 "auth":"Zabbix Auth ID",
 "id": 1,
 })
 #create request object
 request = urllib2.Request(url,data)
 for key in header: 
 request.add_header(key,header[key])
 #get host list
 try:
 result = urllib2.urlopen(request)
 except URLError as e:
 print "The server could not fulfill the request.",e.reason else:
 reponse = json.loads(result.read())
 result.close()
 #print "Number of Hosts:",len(reponse['result'])
 for host in reponse['result']:
  #print "Host ID:",host['hostid'],"Host Name:",host['name']
  zbxhosts=host['name']
  zabbixhostlst.append(zbxhosts)
 zabbixhostlst.sort()
 return zabbixhostlst def main():
 nmaphostlst = nmap_host() 
 zbxhostlst = zabbix_host() 
 diff = list(set(nmaphostlst) ^ set(zbxhostlst)) 
 content = "\n"
 nomonitorlst = [] 
 if len(diff) != 0: 
 for host in diff: 
  if host in nmaphostlst: 
  nomonitorlst.append(host)
 else: 
 sys.exit()
 #print zbxhostlst
 string = '\n'.join(nomonitorlst)
 f = file('/shell/machine/result/result.txt','w')
 f.write(string)
 f.flush()
 f.close()
 runCmd(mail_cmd)if __name__ == "__main__": 
 main()

   把腳本添加到crontab,每臺會收到關(guān)于那些主機沒有添加監(jiān)控的信息。

 總結(jié):

     1)Zabbix API相關(guān)信息可以查看官方詳細資料,看不懂英文的可以參考下面這篇文檔。http://paperplane.ruhoh.com/zabbix/intro-to-zabbix-api/

     2)通過該腳本可以知道那些主機沒有添加監(jiān)控,希望對大家有幫助,如果有更好的解決方法歡迎多多交流。 

以上所述是小編給大家介紹的使用Python腳本實現(xiàn)Zabbix-API 監(jiān)控,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 使用Python實現(xiàn)TCP/IP客戶端和服務(wù)端通信功能

    使用Python實現(xiàn)TCP/IP客戶端和服務(wù)端通信功能

    TCP/IP(傳輸控制協(xié)議/互聯(lián)網(wǎng)協(xié)議)是互聯(lián)網(wǎng)的基礎(chǔ)協(xié)議,用于在網(wǎng)絡(luò)中的計算機之間進行可靠的數(shù)據(jù)傳輸,在Python中,可以使用socket模塊來實現(xiàn)TCP/IP通信,本文給大家介紹了使用Python實現(xiàn)TCP/IP客戶端和服務(wù)端通信功能,需要的朋友可以參考下
    2024-12-12
  • Python數(shù)據(jù)分析之缺失值檢測與處理詳解

    Python數(shù)據(jù)分析之缺失值檢測與處理詳解

    在實際的數(shù)據(jù)處理中,缺失值是普遍存在的,如何使用 Python 檢測和處理缺失值,就是本文要講的主要內(nèi)容。感興趣的同學(xué)可以關(guān)注一下
    2021-12-12
  • python入門字符串拼接\截取\轉(zhuǎn)數(shù)字理解學(xué)習(xí)

    python入門字符串拼接\截取\轉(zhuǎn)數(shù)字理解學(xué)習(xí)

    本篇內(nèi)容我們主要講有關(guān)Python字符串的用法,包括字符串的拼接、字符串怎么轉(zhuǎn)數(shù)字、字符串的格式化、字符串函數(shù)等內(nèi)容,有需要的朋友可以借鑒參考下
    2021-09-09
  • python多進程使用函數(shù)封裝實例

    python多進程使用函數(shù)封裝實例

    這篇文章主要介紹了python多進程使用函數(shù)封裝實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • python中super().__init__()的用法

    python中super().__init__()的用法

    python里的super().__init__()有什么作用?很多同學(xué)沒有弄清楚。super()用來調(diào)用父類(基類)的方法,__init__()是類的構(gòu)造方法,感興趣的小伙伴可以參考閱讀本文
    2023-03-03
  • Python?代碼智能感知類型標(biāo)注與特殊注釋詳解

    Python?代碼智能感知類型標(biāo)注與特殊注釋詳解

    這篇文章主要為大家介紹了Python?代碼智能感知類型標(biāo)注與特殊注釋詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-09-09
  • 使用python3批量下載rbsp數(shù)據(jù)的示例代碼

    使用python3批量下載rbsp數(shù)據(jù)的示例代碼

    這篇文章主要介紹了使用python3批量下載rbsp數(shù)據(jù)的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • python中偏函數(shù)partial用法實例分析

    python中偏函數(shù)partial用法實例分析

    這篇文章主要介紹了python中偏函數(shù)partial用法,實例分析了偏函數(shù)partial的功能、定義及使用方法,需要的朋友可以參考下
    2015-07-07
  • Python處理字節(jié)串:struct.pack和struct.unpack使用

    Python處理字節(jié)串:struct.pack和struct.unpack使用

    這篇文章主要介紹了Python處理字節(jié)串:struct.pack和struct.unpack使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 在CentOS7下安裝Python3教程解析

    在CentOS7下安裝Python3教程解析

    這篇文章主要介紹了在CentOS7下安裝Python3教程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07

最新評論

陈巴尔虎旗| 图木舒克市| 灵璧县| 沾化县| 年辖:市辖区| 黄骅市| 铜山县| 文登市| 卢龙县| 武陟县| 金坛市| 双辽市| 遂平县| 寻甸| 东莞市| 务川| 乌拉特后旗| 讷河市| 鄢陵县| 宁海县| 略阳县| 壤塘县| 大新县| 台湾省| 江华| 榆社县| 民勤县| 吴堡县| 仙居县| 麻城市| 马公市| 安多县| 太湖县| 吉水县| 理塘县| 偏关县| 淮滨县| 德清县| 石林| 庆元县| 湖南省|