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的更多相关文章

  1. python3 调用zabbix API实现批量增加删除主机,主机各种监控项------实战

    在以前的博客中谈到了利用zabbix接口来对主机进行批量的增删改查 这里在不用环境中实战遇到了不同问题,这里记录下来以便后续review 以下为实战中获取token的代码,在zabbix标准接口文档中 ...

  2. python 调用zabbix api接口实现主机的增删改查

    python程序调用zabbix系统的api接口实现对zabbix_server端主机的增删改查,使用相关功能时候,需要打开脚本中的相关函数. 函数说明: zabbixtools()  调用zabbi ...

  3. PHP通过ZABBIX API获取主机信息 VS 直接从数据库获取主机信息

    最近项目需要获取linux主机的一些信息,如CPU使用率,内存使用情况等.由于我们本身就装了zabbix系统,所以我只用知道如何获取信息即可,总结有两种方法可以获取. 一.通过ZABBIX API获取 ...

  4. 利用zabbix api添加、删除、禁用主机

    python环境配置yum -y install python-pip安装argparse模块pip install -i https://pypi.douban.com/simple/ argpar ...

  5. python 调用zabbix api实现查询主机信息,输出所有主机ip

    之前发现搜索出来的主机调用zabbix api信息都不是那么明确,后来通过zabbix官方文档,查到想要的api信息,随后写一篇自己这次项目中用到的api. #!/usr/bin/env python ...

  6. 03: zabbix API接口 对 主机、主机组、模板、应用集、监控项、触发器等增删改查

    目录:Django其他篇 01: 安装zabbix server 02:zabbix-agent安装配置 及 web界面管理 03: zabbix API接口 对 主机.主机组.模板.应用集.监控项. ...

  7. Zabbix Api的使用

    API使用 zabbix官网文档:https://www.zabbix.com/documentation/2.2/manual/api, Zabbix API是基于JSON-RPC 2.0规格,具体 ...

  8. 基于curl 的zabbix API调用

    1,认证并取得加密字段 curl -i -X POST -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0&q ...

  9. PHP通过Zabbix API获取服务器监控信息

    开源监控系统Zabbix提供了丰富的API,供第三方系统调用. 基本步骤如下: 1.获取合法认证:连接对应Zabbix URL,并提供用户名和密码,HTTP方法为"POST",HT ...

随机推荐

  1. Entity Framework Core 1.1 升级通告

    原文地址:https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-entity-framework-core-1-1/ 翻译:杨晓东 ...

  2. 46张PPT讲述JVM体系结构、GC算法和调优

    本PPT从JVM体系结构概述.GC算法.Hotspot内存管理.Hotspot垃圾回收器.调优和监控工具六大方面进行讲述.(内嵌iframe,建议使用电脑浏览) 好东西当然要分享,PPT已上传可供下载 ...

  3. 伪共享(false sharing),并发编程无声的性能杀手

    在并发编程过程中,我们大部分的焦点都放在如何控制共享变量的访问控制上(代码层面),但是很少人会关注系统硬件及 JVM 底层相关的影响因素.前段时间学习了一个牛X的高性能异步处理框架 Disruptor ...

  4. 视频 - 在 VirtualBox 中部署 OpenStack

    大家新年好,CloudMan 今天给大家带来一件新年礼物. 一直以来大家都反馈 OpenStack 学习有两大障碍:1. 实验环境难搭2. 体系复杂,难道大今天我就先帮大家解决环境问题.前两天我抽空在 ...

  5. mybatis_映射查询

    一.一对一映射查询: 第一种方式(手动映射):借助resultType属性,定义专门的pojo类作为输出类型,其中该po类中封装了查询结果集中所有的字段.此方法较为简单,企业中使用普遍. <!- ...

  6. UWP开发之Mvvmlight实践九:基于MVVM的项目架构分享

    在前几章介绍了不少MVVM以及Mvvmlight实例,那实际企业开发中将以那种架构开发比较好?怎样分层开发才能节省成本? 本文特别分享实际企业项目开发中使用过的项目架构,欢迎参照使用!有不好的地方欢迎 ...

  7. git 命令总结

    1 删除分支 git push origin :branch name(Task_******) //删除远程分支 git branch -D branch name(Task_******)     ...

  8. 在将 varchar 值 'xinpian' 转换成数据类型 int 时失败?

    把int类型的值修改为varchar类型的值

  9. 如何使用dos命令查看MySQL当前使用的数据库?

    1.dos命令安装mysqld --stall.启动net start mysql.进入MySQL数据库mysql -uroot -p后,输入select database(); 如图:

  10. v14.0\AspNet\Microsoft.Web.AspNet.Props 找不到

    错误 E:\Github\AutoMapper\src\AutoMapper\AutoMapper.CoreCLR.kproj : error  : 未找到导入的项目"C:\Program ...