python通过zabbix api获取主机

yipeiwu_com5年前Python基础

zabbix强大地方在于有强大的api,zabbix 的api可以拿到zabbix大部分数据,目前我所需的数据基本可以通过api获取,以下是通过zabbix api获取的主机信息python代码,其他数据也如此类推,api使用方法可参见官网文档

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import json
import urllib2
from urllib2 import URLError
from login import zabbix_login
t=zabbix_login()
def hostid_get():
 data = json.dumps(
  {
   "jsonrpc": "2.0",
   "method": "host.get",
   "params": {
      "output": "extend",
      "groupids":14,
      "filter":{"flags": "4" },
      },
   "auth":t.user_login(),
   "id": 1,
  })
 request = urllib2.Request(t.url, data)
 for key in t.header:
  request.add_header(key, t.header[key])
 try:
  result = urllib2.urlopen(request)
 except URLError as e:
  if hasattr(e, 'reason'):
   print 'zabbix server is faile'
   print 'Reason: ', e.reason
  elif hasattr(e, 'code'):
   print 'zabbix server not request.'
   print 'Error code: ', e.code
 else:
  response = json.loads(result.read())
  result.close()
  hostid=[]
  hostname=[]
  for host in response['result']:
   hostid.append(host['hostid'])
   hostname.append(host['name'])
  return hostid,hostname
 
if __name__ == "__main__":
 a,b=hostid_get()
 i=0
 n=len(b)
 for i in range(n):
  print a[i],b[i]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在PYQT5中QscrollArea(滚动条)的使用方法

在PYQT5中QscrollArea(滚动条)的使用方法

如下所示: import sys from PyQt5.QtWidgets import * class MainWindow(QMainWindow): def __in...

全面了解django的缓存机制及使用方法

全面了解django的缓存机制及使用方法

一、缓存目的 1、减小过载 2、避免重复计算 3、提高系统性能 二、如何进行缓存 三、缓存类型 四、缓存粒度分类 五、缓存的设置与使用 示例一: CACHES = {  ...

Python实现拼接多张图片的方法

本文实例讲述了Python实现拼接多张图片的方法。分享给大家供大家参考。具体分析如下:   这里所述计划实现如下操作:   ① 用Latex写原始博文,生成PDF文档...

Python中将dataframe转换为字典的实例

有时候,在Python中需要将dataframe类型转换为字典类型,下面的方法帮助我们解决这一问题。 任务代码。 # encoding: utf-8 import pandas a...

python3.6下Numpy库下载与安装图文教程

python3.6下Numpy库下载与安装图文教程

今天在做Plotly的散点图时,需要Numpy 这个库的使用。 没有安装Numpy这个库的时候,报错一般是下图这样:ModuleNotFoundError: No module name...