285572001 发表于 2019-1-20 11:00:32

Zabbix 调用API 批量添加主机到主机组中 (读取Excel)

# !/usr/bin/env python  # coding:utf-8
  import json
  import urllib2
  from urllib2 import URLError
  import xlrd
  import sys
  import copy
  import os
  class zabbixtools:
  def __init__(self):
  self.url = "http://zb3.com/api_jsonrpc.php"
  self.header = {"Content-Type": "application/json"}
  self.authID = self.user_login()
  def user_login(self):
  data = json.dumps(
  {
  "jsonrpc": "2.0",
  "method": "user.login",
  "params": {
  "user": "user",
  "password": "password"
  },
  "id": 0
  })
  request = urllib2.Request(self.url,data)
  for key in self.header:
  request.add_header(key,self.header)
  try:
  result = urllib2.urlopen(request)
  except URLError as e:
  print "Auth Failed, Please Check Your Name And Password:",e.code
  else:
  response = json.loads(result.read())
  result.close()
  authID = response['result']
  return authID
  def get_data(self,data,hostip=""):
  request = urllib2.Request(self.url,data)
  for key in self.header:
  request.add_header(key,self.header)
  try:
  result = urllib2.urlopen(request)
  except URLError as e:
  if hasattr(e, 'reason'):
  print 'We failed to reach a server.'
  print 'Reason: ', e.reason
  elif hasattr(e, 'code'):
  print 'The server could not fulfill the request.'
  print 'Error code: ', e.code
  return 0
  else:
  response = json.loads(result.read())
  result.close()
  return response
  def host_get(self,hostip):
  # hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
  data = json.dumps(
  {
  "jsonrpc": "2.0",
  "method": "host.get",
  "params": {
  "output": ["hostid", "name", "status", "host","groupids"],
  "selectGroups": "extend",
  "filter": {"host": }
  },
  "auth": self.authID,
  "id": 1
  })
  res = self.get_data(data)['result']
  if (res != 0) and (len(res) != 0):
  # for host in res:
  print type(res)
  host = res
  # return host['groups']['groupid']
  # return host['hostid']
  return host
  else:
  return ""
  def host_get_group(self,hostip):
  group_list = []
  # hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
  data = json.dumps(
  {
  "jsonrpc": "2.0",
  "method": "host.get",
  "params": {
  "output": ["hostid", "name", "status", "host","groupids"],
  "selectGroups": "extend",
  "filter": {"host": }
  },
  "auth": self.authID,
  "id": 1
  })
  res = self.get_data(data)['result']
  if (res != 0) and (len(res) != 0):
  print type(res)
  groups = res['groups']
  for group in groups:
  var = {}
  var['groupid'] = group['groupid']
  group_list.append(var)
  # return host['groups']['groupid']
  return group_list
  else:
  return ""
  def hostgroup_get(self,hostgroupName):
  data = json.dumps(
  {
  "jsonrpc": "2.0",
  "method": "hostgroup.get",
  "params": {
  "output": "extend",
  "filter": {"name": }
  },
  "auth": self.authID,
  "id": 1
  })
  res = self.get_data(data)['result']
  if (res != 0) and (len(res) != 0):
  # for host in res:
  print type(res)
  host = res
  return host['groupid']
  else:
  return ""
  def host_update(self,hostIp,hostgroupName):
  print hostIp,hostgroupName
  data = json.dumps({
  "jsonrpc": "2.0",
  "method": "host.update",
  "params": {
  # "hostid": '10202',
  "hostid": self.host_get(hostIp)['hostid'],
  "groups": hostgroupName,
  "status": 0,
  },
  "auth": self.authID,
  "id": 1
  })
  res = self.get_data(data)['result']
  if (res != 0) and (len(res) != 0):
  # for host in res:
  print type(res)
  # print res['hostids']
  return res['hostids']
  else:
  return ""
  if __name__ == "__main__":
  test = zabbixtools()
  workbook = xlrd.open_workbook('addhost_to_hostgroup.xlsx')
  for row in xrange(workbook.sheets().nrows):
  hostIp = workbook.sheets().cell(row, 0).value
  hostgroupName = workbook.sheets().cell(row, 1).value
  hostgroup_old = test.host_get_group(hostIp)
  #获取目前主机的所属组
  hostgroup_id = test.hostgroup_get(hostgroupName)
  hostgroup_new = [{'groupid': hostgroup_id}]
  #判断新增的组是否存在目前主机的所属组
  for groupid inhostgroup_new:
  if groupid not in hostgroup_old:
  hostgroup_old_format = copy.deepcopy(hostgroup_old)
  hostgroup_old_format.append(groupid)
  print hostgroup_old_format
  test.host_update(hostIp,hostgroup_old_format)

页: [1]
查看完整版本: Zabbix 调用API 批量添加主机到主机组中 (读取Excel)