python通过zabbix api获取主机

yipeiwu_com6年前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设计】。

相关文章

详解Python最长公共子串和最长公共子序列的实现

详解Python最长公共子串和最长公共子序列的实现

最长公共子串(The Longest Common Substring) LCS问题就是求两个字符串最长公共子串的问题。解法就是用一个矩阵来记录两个字符串中所有位置的两个字符之间的匹配情...

python+pyqt实现右下角弹出框

python+pyqt实现右下角弹出框

本文实例为大家分享了pyqt实现右下角弹出框的具体代码,供大家参考,具体内容如下 构造函数中: self.desktop=QDesktopWidget() self.move((...

浅谈python中str字符串和unicode对象字符串的拼接问题

str字符串 s = '中文' # s: <type 'str'> s是个str对象,中文字符串。存储方式是字节码。字节码是怎么存的: 如果这行代码在python解释...

mac系统安装Python3初体验

前沿 对于iOS开发不要随便拆卸系统自带的Python,因为有很多 library 还是使用 Python2.7。 1 安装Xcode 1.1 App Store 搜索Xcode 并安装...

python使用tkinter实现简单计算器

本文实例为大家分享了python使用tkinter实现简单计算器的具体代码,供大家参考,具体内容如下 class Counter: #引入tkinter import tki...