设为首页 收藏本站
查看: 677|回复: 0

[经验分享] zabbix api脚本

[复制链接]

尚未签到

发表于 2019-1-18 08:24:47 | 显示全部楼层 |阅读模式
import simplejson as json  
import urllib2, subprocess, re, time
  
class ZabbixAPIException(Exception):
  pass
  
class ZabbixAPI(object):
  __auth = ''
  __id = 0
  _state = {}
  def __new__(cls, *args, **kw):
  if not cls._state.has_key(cls):
  cls._state[cls] = super(ZabbixAPI, cls).__new__(cls, *args, **kw)
  return cls._state[cls]
  def __init__(self, url, user, password):
  self.__url = url.rstrip('/') + '/api_jsonrpc.php'
  self.__user = user
  self.__password = password
  self._zabbix_api_object_list = ('Action', 'Alert', 'APIInfo', 'Application', 'DCheck', 'DHost', 'DRule',
  'DService', 'Event', 'Graph', 'Grahpitem', 'History', 'Host', 'Hostgroup', 'Image', 'Item',
  'Maintenance', 'Map', 'Mediatype', 'Proxy', 'Screen', 'Script', 'Template', 'Trigger', 'User',
  'Usergroup', 'Usermacro', 'Usermedia')
  def __getattr__(self, name):
  if name not in self._zabbix_api_object_list:
  raise ZabbixAPIException('No such API object: %s' % name)
  if not self.__dict__.has_key(name):
  self.__dict__[name] = ZabbixAPIObjectFactory(self, name)
  return self.__dict__[name]
  def login(self):
  user_info = {'user'     : self.__user,
  'password' : self.__password}
  obj = self.json_obj('user.login', user_info)
  content = self.postRequest(obj)
  try:
  self.__auth = content['result']
  except KeyError, e:
  e = content['error']['data']
  raise ZabbixAPIException(e)
  def isLogin(self):
  return self.__auth != ''
  def __checkAuth__(self):
  if not self.isLogin():
  raise ZabbixAPIException("NOT logged in")
  def json_obj(self, method, params):
  obj = { 'jsonrpc' : '2.0',
  'method'  : method,
  'params'  : params,
  'auth'    : self.__auth,
  'id'      : self.__id}
  return json.dumps(obj)
  def postRequest(self, json_obj):
  #print 'Post: %s' % json_obj
  headers = { 'Content-Type' : 'application/json-rpc',
  'User-Agent'   : 'python/zabbix_api'}
  req = urllib2.Request(self.__url, json_obj, headers)
  opener = urllib2.urlopen(req)
  content = json.loads(opener.read())
  self.__id += 1
  #print 'Receive: %s' % content
  return content
  '''
  /usr/local/zabbix/bin/zabbix_get is the default path to zabbix_get, it depends on the 'prefix' while install zabbix.
  plus, the ip(computer run this script) must be put into the conf of agent.
  '''
  @staticmethod
  def zabbixGet(ip, key):
  zabbix_get = subprocess.Popen('/apps/svr/zabbix/bin/zabbix_get  -s %s -k %s' % (ip, key), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  result, err = zabbix_get.communicate()
  if err:
  return 'ERROR'
  return result.strip()
  def createObject(self, object_name, *args, **kwargs):
  return object_name(self, *args, **kwargs)
  def getHostByHostid(self, hostids):
  if not isinstance(hostids,list):
  hostids = [hostids]
  return [dict['host'] for dict in self.host.get({'hostids':hostids,'output':'extend'})]
  
#################################################
  
#    Decorate Method
  
#################################################
  
def checkAuth(func):
  def ret(self, *args):
  self.__checkAuth__()
  return func(self, args)
  return ret
  
def postJson(method_name):
  def decorator(func):
  def wrapper(self, params):
  try:
  content = self.postRequest(self.json_obj(method_name, params))
  return content['result']
  except KeyError, e:
  e = content['error']['data']
  raise ZabbixAPIException(e)
  return wrapper
  return decorator
  
def ZabbixAPIObjectMethod(func):
  def wrapper(self, method_name, params):
  try:
  content = self.postRequest(self.json_obj(method_name, params))
  return content['result']
  except KeyError, e:
  e = content['error']['data']
  raise ZabbixAPIException(e)
  return wrapper
  
#################################################
  
#    Zabbix API Object (host, item...)
  
#################################################
  
class ZabbixAPIObjectFactory(object):
  def __init__(self, zapi, object_name=''):
  self.__zapi = zapi
  self.__object_name = object_name
  def __checkAuth__(self):
  self.__zapi.__checkAuth__()
  def postRequest(self, json_obj):
  return self.__zapi.postRequest(json_obj)
  def json_obj(self, method, param):
  return self.__zapi.json_obj(method, param)
  def __getattr__(self, method_name):
  def method(params):
  return self.proxyMethod('%s.%s' % (self.__object_name,method_name), params)
  return method
  # 'find' method is a wrapper of get. Difference between 'get' and 'find' is that 'find' can create object you want while it dosn't exist
  def find(self, params, attr_name=None, to_create=False):
  filtered_list = []
  result = self.proxyMethod('%s.get' % self.__object_name, {'output':'extend','filter': params})
  if to_create and len(result) == 0:
  result = self.proxyMethod('%s.create' % self.__object_name, params)
  return result.values()[0]
  if attr_name is not None:
  for element in result:
  filtered_list.append(element[attr_name])
  return filtered_list
  else:
  return result
  @ZabbixAPIObjectMethod
  @checkAuth
  def proxyMethod(self, method_name, params):
  pass
  
def testCase():
  zapi = ZabbixAPI(url='xxxx', user='xxxx', password='xxxx')
  zapi.login()
  print zapi.Graph.find({'graphid':'221'}, attr_name='graphid')[0]
  #hostid = zapi.Host.find({'ip':'xxxxxx'}, attr_name='hostid')[0]
  print zapi.Host.find({'ip':'10.200.100.25'})
  print zapi.Host.exists({'filter':{'host':'GD9-DNS-001'}})
  #host = zapi.createObject(Host, 'HostToCreate')
  #item = host.getItem('444107')
  #zapi.host.get({'hostids':['16913','17411'],'output':'extend'})
  #group = zapi.createObject(Hostgroup, '926')
  #print zapi.getHostByHostid('16913')
  
if __name__ == '__main__':
  testCase()



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-664594-1-1.html 上篇帖子: Grafana plugins zabbix 安装 下篇帖子: zabbix修改之中文主机名
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表