通过Zabbix API实现对主机的增加(无主机资产的添加和带主机资产的添加)、删除、获取主机id、获取模板id、获取组id

config.yaml存储zabbix的信息(主要包括zabbix server的url 、请求头部、登陆的用户名密码)

Zabbix_Config:
zabbix_url: http://192.168.1.179/zabbix/api_jsonrpc.php
zabbix_header: {"Content-Type": "application/json"}
zabbix_user: Admin
zabbix_pass: zabbix

auth.py文件,主要是获取zabbix认证id和对zabbix的请求,包括根据主机名(host_name)或者可见名(visible_name)获取主机的id 、新增主机、新增带资产主机、主机资产变更

#/usr/bin/env python
# encoding: utf-8
import json
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
import yaml def Zabbix_Url_Request(zabbix_url,data,zabbix_header,*args,**kwargs):
#print data
# create request object
request = urllib2.Request(zabbix_url, data, zabbix_header)
try:
result = urllib2.urlopen(request)
# 对于出错新的处理
except HTTPError, e:
print 'The server couldn\'t fulfill the request, Error code: ', e.code
except URLError, e:
print 'We failed to reach a server.Reason: ', e.reason
else:
response = json.loads(result.read())
#print response
return response
result.close() def Zabbix_Auth_Code(zabbix_url,zabbix_header,*args,**kwargs):
with open('config.ymal') as f:
result = yaml.load(f)
result_zabbix_info = result['Zabbix_Config']
zabbix_user = result_zabbix_info['zabbix_user']
zabbix_pass = result_zabbix_info['zabbix_pass']
# auth user and password
# 用户认证信息的部分,最终的目的是得到一个SESSIONID
# 这里是生成一个json格式的数据,用户名和密码
auth_data = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.login",
"params":
{
"user": zabbix_user,
"password": zabbix_pass
},
"id": 0
})
response = Zabbix_Url_Request(zabbix_url,auth_data,zabbix_header)
# print response
if 'result' in response:
#print response
return response['result'],response['id'] else:
print response['error']['data']

host_info.py 对zabbix的主机的操作

 #/usr/bin/env python
# encoding: utf-8
import json
import sys
from auth import Zabbix_Auth_Code,Zabbix_Url_Request
#zabbix_url = "http://192.168.1.179/zabbix/api_jsonrpc.php"
#zabbix_header = {"Content-Type": "application/json"}
class Host_Action(object):
def __init__(self,zabbix_url,zabbix_header,host_name=None,visible_name=None,*args,**kwargs):
'''
实现的功能:获取主机id,增、删主机,更新zabbix主机资产表
:param zabbix_url: 访问zabbix的URL
:param zabbix_header: 访问头部
:param host_name: hostname
:param visible_name: 可见的主机名
:param args:
:param kwargs:
'''
self.zabbix_url = zabbix_url
self.zabbix_header = zabbix_header
self.host_name= host_name
self.visible_name = visible_name
def Get_Host_Id(self):
auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
find_info = {}
find_info['host'] = [self.host_name]
find_info['name'] = [self.visible_name]
for k,v in find_info.items():
if v[0] == None:
find_info.pop(k)
get_host_id_data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter": find_info
},
"auth": auth_code,
"id": auth_id
})
host_info = Zabbix_Url_Request(zabbix_url=self.zabbix_url,data=get_host_id_data,zabbix_header=self.zabbix_header)
print host_info
if len(host_info['result']) != 0:
hostid = host_info['result'][0]['hostid']
#print hostid
return hostid
else:
print '没有查询到主机hostids'
return 0
def Add_Host(self,host_ip,template_id=10001,group_id=2,type=1,main=1,userip=1,port="",dns="",
flag=0,host_inventory=None,*args,**kwargs):
''' :param group_id: 主机关联的监控模本id(groupid)
:param templateid: 主机关联的监控模板id(templateid)
:param host_ip: 主机ip地址
:param type: 1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX
:param main: 0 - not default; 1 - default
:param userip: 0 - connect using host DNS name; 1 - connect using host IP address for this host interface.
:param port: Port number used by the interface
:param dns: 0 - connect using host DNS name;1 - connect using host IP address for this host interface.
:param flag: 是否维护主机资产,0 - 表示不录入;1 - 表示录入
:param host_inventory: 主机资产表
:param args:
:param kwargs:
:return:
'''
self.host_ip = host_ip
self.type = type
self.main = main
self.userip = userip
self.port = port
self.flag = flag
self.dns = dns
self.host_inventory = host_inventory
host_msg = {}
if self.host_name == None:
self.host_name = self.host_ip
host_template_info =[{"templateid": template_id}]
host_group_info = [{"groupid": group_id}]
host_interfaces_info = [{
"type": self.type,
"main": self.main,
"useip": self.userip,
"ip": self.host_ip,
"dns": self.dns,
"port": self.port
}]
host_msg['host'] = self.host_name
host_msg['name'] = self.visible_name
host_msg['interfaces'] = host_interfaces_info
host_msg['groups'] = host_group_info
host_msg['templates'] = host_template_info
if self.flag == 0:
host_msg['inventory_mode'] = -1 # -1 - disabled; 0 - (default) manual; 1 - automatic.
elif self.flag == 1:
host_msg['inventory_mode'] = 0 # -1 - disabled; 0 - (default) manual; 1 - automatic.
else:
sys.exit(1)
auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
host_info = json.dumps({
"jsonrpc": "2.0",
"method": "host.create",
"params": host_msg,
"auth": auth_code,
"id": auth_id
})
add_host = Zabbix_Url_Request(zabbix_url=self.zabbix_url,data=host_info,zabbix_header=self.zabbix_header)
if add_host['result']['hostids']:
print "增加被监控主机成功,主机id : %s"%(add_host['result']['hostids']) def Del_Host(self,host_id):
self.host_id = host_id
auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
del_host_info = json.dumps({
"jsonrpc": "2.0",
"method": "host.delete",
"params": [
self.host_id,
],
"auth": auth_code,
"id": auth_id
})
host_del = Zabbix_Url_Request(self.zabbix_url,del_host_info,self.zabbix_header)
print host_del
#if host_del['error'] if host_del['result']['hostids'] == self.host_id:
print 'id为%s主机删除成功!!!'%self.host_id def Update_Host_Ienventory(self,host_id,host_inventory,*args,**kwargs):
self.host_id = host_id
self.host_inventory = host_inventory
auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
host_msg = {}
host_msg['hostid'] = self.host_id
host_msg['inventory_mode'] = 0
host_msg['inventory'] = self.host_inventory update_msg = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.update",
"params": host_msg,
"auth": auth_code,
"id": auth_id
}
)
update_host_ienventory = Zabbix_Url_Request(zabbix_url=self.zabbix_url,data=update_msg,zabbix_header=self.zabbix_header)
print update_host_ienventory def Get_Group_Id(group_name,zabbix_url,zabbix_header,*args,**kwargs):
'''
通过组名获取组id
:param group_name: 组名
:return:
'''
auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=zabbix_url,zabbix_header=zabbix_header)
group_info = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": [
group_name,
]
}
},
"auth":auth_code,
"id": auth_id
})
groups_result = Zabbix_Url_Request(zabbix_url=zabbix_url,data=group_info, zabbix_header=zabbix_header)
#print groups_result['result'][0]['groupid']
return groups_result['result'][0]['groupid'] def Get_Template_Id(template_name,zabbix_url,zabbix_header,*args,**kwargs):
'''
通过模板名获取组id
:param template_name: 模板名
:return:
'''
auth_code,auth_id = Zabbix_Auth_Code(zabbix_url=zabbix_url,zabbix_header=zabbix_header)
template_info = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"host": [
template_name
]
}
},
"auth": auth_code,
"id": auth_id
})
template_result = Zabbix_Url_Request(zabbix_url=zabbix_url,date=template_info,zabbix_header= zabbix_header)
#print template_result['result'][0]['templateid']
return template_result['result'][0]['templateid']

index.py 程序入口

 #/usr/bin/env python
# encoding: utf-8
import yaml
from host_info import Host_Action,Get_Group_Id,Get_Template_Id
import sys
reload(sys)
sys.setdefaultencoding('utf8') if __name__ == '__main__':
try:
with open('config.ymal') as f:
result = yaml.load(f)
result_zabbix_info = result['Zabbix_Config']
zabbix_url = result_zabbix_info['zabbix_url']
zabbix_header = result_zabbix_info['zabbix_header'] #删除主机
host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84',
visible_name='t1')
host_id = host.Get_Host_Id()
host.Del_Host(host_id)
#增加主机不带资产
host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84',visible_name='t1')
host.Add_Host(host_ip='192.168.1.84') #获取指定主机的hostid
host = Host_Action(zabbix_url=zabbix_url,zabbix_header=zabbix_header,host_name='192.168.1.84')
host_id = host.Get_Host_Id()
print '主机192.168.1.84的id是: %s'%host_id #获取指定模本的id
t_id = Get_Template_Id(template_name='Template OS Linux',zabbix_header=zabbix_header,zabbix_url=zabbix_url)
print "模板Template OS Linux的id是:%s"%t_id #获取指定组的id
Get_Group_Id(group_name='Linux servers',zabbix_header=zabbix_header,zabbix_url=zabbix_url)
print "组Linux servers的id是:%s" % t_id host_inventory = {
"type": "Linux Server",
"name": "xxxxxxx",
"os": "centos7.2",
"os_full": "RedHat Centos 7.2",
"os_short": "Centos 7.2",
"serialno_a": "f729d3fa-fd53-4c5f-8998-67869dad349a",
"macaddress_a": "00:16:3e:03:af:a0",
"hardware_full": "cpu: 4c; 内存: 8G; 硬盘: 20G",
"software_app_a": "docker",
"software_app_b": "zabbix agent",
"software_full": "docker zabbix-server ntpd",
"contact": "xxx", # 联系人
"location": "阿里云 华北二", # 位置
"vendor": "阿里云", # 提供者
"contract_number": "", # 合同编号
"installer_name": "xx 手机: xxxxxxxxxx", # 安装名称
"deployment_status": "prod",
"host_networks": "192.168.1.179",
"host_netmask": "255.255.255.0",
"host_router": "192.168.1.1",
"date_hw_purchase": "2016-07-01", # 硬件购买日期
"date_hw_install": "2016-07-01", # 硬件购买日期
"date_hw_expiry": "0000-00-00", # 硬件维修过期
"date_hw_expiry": "0000-00-00", # 硬件维修过期
"date_hw_decomm": "0000-00-00", # 硬件报废时间
"site_city": "北京",
"site_state": "北京",
"site_country": "中国",
"site_zip": "", # 邮编
"site_rack": "", # 机架
} #添加带资产的主机
host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84')
host_id = host.Get_Host_Id(host_inventory=host_inventory,flag=1) # 删除主机
host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84',
visible_name='t1')
host_id = host.Get_Host_Id()
host.Del_Host(host_id) except Exception,e:
print e

部分执行结果如下:

增加被监控主机成功,主机id : [u'10116']
主机192.168.1.84的id是: 10115
模板Template OS Linux的id是:10001

组Linux servers的id是:10001
资产情况如下图:

通过Zabbix API实现对主机的增加(无主机资产的添加和带主机资产的添加)、删除、获取主机id、获取模板id、获取组id

上一篇:ios——MPMoviePlayerController截取视频缩略图 播放视频又可以截取视频缩略图


下一篇:linux设备和驱动加载的先后顺序