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. CoreCLR源码探索(一) Object是什么

    .Net程序员们每天都在和Object在打交道 如果你问一个.Net程序员什么是Object,他可能会信誓旦旦的告诉你"Object还不简单吗,就是所有类型的基类" 这个答案是对的 ...

  2. 关于.NET异常处理的思考

    年关将至,对于大部分程序员来说,马上就可以闲下来一段时间了,然而在这个闲暇的时间里,唯有争论哪门语言更好可以消磨时光,估计最近会有很多关于java与.net的博文出现,我表示要作为一个吃瓜群众,静静的 ...

  3. Python高手之路【一】初识python

    Python简介 1:Python的创始人 Python (英国发音:/ˈpaɪθən/ 美国发音:/ˈpaɪθɑːn/), 是一种解释型.面向对象.动态数据类型的高级程序设计语言,由荷兰人Guido ...

  4. 计算机程序的思维逻辑 (60) - 随机读写文件及其应用 - 实现一个简单的KV数据库

    57节介绍了字节流, 58节介绍了字符流,它们都是以流的方式读写文件,流的方式有几个限制: 要么读,要么写,不能同时读和写 不能随机读写,只能从头读到尾,且不能重复读,虽然通过缓冲可以实现部分重读,但 ...

  5. 计算机程序的思维逻辑 (54) - 剖析Collections - 设计模式

    上节我们提到,类Collections中大概有两类功能,第一类是对容器接口对象进行操作,第二类是返回一个容器接口对象,上节我们介绍了第一类,本节我们介绍第二类. 第二类方法大概可以分为两组: 接受其他 ...

  6. Adaboost提升算法从原理到实践

    1.基本思想: 综合某些专家的判断,往往要比一个专家单独的判断要好.在"强可学习"和"弱科学习"的概念上来说就是我们通过对多个弱可学习的算法进行"组合 ...

  7. scp报错 -bash: scp: command not found

    环境:RHEL6.5 使用scp命令报错: [root@oradb23 media]# scp /etc/hosts oradb24:/etc/ -bash: scp: command not fou ...

  8. 卸载oracle之后,如何清除注册表

    之前卸载了oracle,今天偶然间发现,在服务和应用程序里面,还残存着之前的oracle服务.原来,还需要去清理下注册表. 在开始菜单的这个框里面 输入regedit,进入注册表.找到这个目录 HKE ...

  9. python10作业思路及源码:类Fabric主机管理程序开发(仅供参考)

    类Fabric主机管理程序开发 一,作业要求 1, 运行程序列出主机组或者主机列表(已完成) 2,选择指定主机或主机组(已完成) 3,选择主机或主机组传送文件(上传/下载)(已完成) 4,充分使用多线 ...

  10. golang sync.WaitGroup bug

    注意,这个结构体,要是想在函数之间传来传去的话,必须要使用指针....... 这个结构体里没有 指针,这个类型可以说没有“引用特性”. 被坑了一晚上.特此记录.