python 调用zabbix api接口实现主机的增删改查
python程序调用zabbix系统的api接口实现对zabbix_server端主机的增删改查,使用相关功能时候,需要打开脚本中的相关函数。
函数说明:
zabbixtools() 调用zabbix api
template_get() 获取zabbix server端已经配置的模板信息
hostgroup_get() 获取已经添加的主机组列表信息
host_get() 单个主机信息
host_del() 删除主机
host_create() 新建主机
get_grouphost() 获取某个组下面所有的主机信息
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib2
import sys
class zabbixtools:
def __init__(self):
self.url = "http://x.x.x.x/zabbix/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": "Admin",
"password": "xxxx"
},
"id": 0
})
request = urllib2.Request(self.url,data)
for key in self.header:
request.add_header(key,self.header[key])
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[key])
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"],
"filter": {"host": [hostip]}
},
"auth": self.authID,
"id": 1
})
res = self.get_data(data)['result']
if (res != 0) and (len(res) != 0):
#for host in res:
host = res[0]
if host['status'] == '':
print "\t","\033[1;31;40m%s\033[0m" % "Host_IP:","\033[1;31;40m%s\033[0m" %host['host'].ljust(15),'\t',"\033[1;31;40m%s\033[0m" % "Host_Name:","\033[1;31;40m%s\033[0m"% host['name'].encode('GBK'),'\t',"\033[1;31;40m%s\033[0m" % u'unmonitor'.encode('GBK')
return host['hostid']
elif host['status'] == '':
print "\t","\033[1;32;40m%s\033[0m" % "Host_IP:","\033[1;32;40m%s\033[0m" %host['host'].ljust(15),'\t',"\033[1;32;40m%s\033[0m" % "Host_Name:","\033[1;32;40m%s\033[0m"% host['name'].encode('GBK'),'\t',"\033[1;32;40m%s\033[0m" % u'monitor'.encode('GBK')
return host['hostid']
else:
print '\t',"\033[1;31;40m%s\033[0m" % "Get Host Error or cannot find this host,please check !"
return 0
def get_grouphost(self):
groupid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your groupid:')
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"host.get",
"params":{
"output":["hostid","name","status","host"],
#"output": "extend",
"groupids":groupid,
},
"auth": self.authID,
"id":1,
})
res = self.get_data(data)
if 'result' in res.keys():
res = res['result']
if (res !=0) or (len(res) != 0):
print "\033[1;32;40m%s\033[0m" % "Number Of Hosts: ","\033[1;31;40m%d\033[0m" % len(res)
for host in res:
print "Host ID:",host['hostid'],"Visible name:",host['name'],"Host-status:",host['status'],"HostName:",host['host']
else:
print "The groupid does not exist, please check!" def host_del(self):
hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
hostid = self.host_get(hostip)
print hostid
if hostid == 0:
print '\t',"\033[1;31;40m%s\033[0m" % "This host cannot find in zabbix,please check it !"
sys.exit()
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.delete",
"params": [hostid],
"auth": self.authID,
"id": 1
})
res = self.get_data(data)['result']
if 'hostids' in res.keys():
print "\t","\033[1;32;40m%s\033[0m" % "Delet Host:%s success !" % hostip
else:
print "\t","\033[1;31;40m%s\033[0m" % "Delet Host:%s failure !" % hostip
def hostgroup_get(self):
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
},
"auth": self.authID,
"id": 1,
})
res = self.get_data(data)
if 'result' in res.keys():
res = res['result']
if (res !=0) or (len(res) != 0):
print "\033[1;32;40m%s\033[0m" % "Number Of Group: ","\033[1;31;40m%d\033[0m" % len(res)
for host in res:
print"\t","HostGroup_id:",host['groupid'],"\t","HostGroup_Name:",host['name'].encode('GBK')
else:
print "Get HostGroup Error,please check !"
def template_get(self):
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
},
"auth": self.authID,
"id": 1,
})
res = self.get_data(data)#['result']
if 'result' in res.keys():
res = res['result']
if (res !=0) or (len(res) != 0):
print "\033[1;32;40m%s\033[0m" % "Number Of Template: ","\033[1;31;40m%d\033[0m" % len(res)
for host in res:
print"\t","Template_id:",host['templateid'],"\t","Template_Name:",host['name'].encode('GBK')
else:
print "Get Template Error,please check !"
def host_create(self):
hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Host_ip :')
#Visible_name = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Visible name :')
groupid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Group_id :')
templateid = raw_input("\033[1;35;40m%s\033[0m" % 'Enter your:Tempate_id :')
g_list=[]
t_list=[]
for i in groupid.split(','):
var = {}
var['groupid'] = i
g_list.append(var)
for i in templateid.split(','):
var = {}
var['templateid'] = i
t_list.append(var)
if hostip and groupid and templateid:
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": hostip,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": hostip,
"dns": "",
"port": ""
}
],
"groups": g_list,
"templates": t_list,
},
"auth": self.authID,
"id": 1,
})
res = self.get_data(data,hostip)
if 'result' in res.keys():
res = res['result']
if 'hostids' in res.keys():
print "\033[1;32;40m%s\033[0m" % "Create host success"
else:
print "\033[1;31;40m%s\033[0m" % "Create host failure: %s" % res['error']['data']
else:
print "\033[1;31;40m%s\033[0m" % "Enter Error: ip or groupid or tempateid is NULL,please check it !"
def main():
test = zabbixtools()
test.template_get()
test.hostgroup_get()
#test.host_get()
#test.host_del()
test.host_create()
#test.get_grouphost()
if __name__ == "__main__":
main()
python 调用zabbix api接口实现主机的增删改查的更多相关文章
- 关于python调用zabbix api接口
因公司业务需要,引进了自动化运维,所用到的监控平台为zbbix3.2,最近正在学习python,计划使用python调用zabbix api接口去做些事情,如生成报表,我想最基本的是要取得zabbix ...
- python 调用zabbix api实现查询主机信息,输出所有主机ip
之前发现搜索出来的主机调用zabbix api信息都不是那么明确,后来通过zabbix官方文档,查到想要的api信息,随后写一篇自己这次项目中用到的api. #!/usr/bin/env python ...
- Python调用zabbix API批量添加主机 (读取Excel)
本文转载自:http://blog.mreald.com/178 Zabbix可以通过自发现添加主机,不过有时候不准确,通过API添加会更加准确! 脚本使用的跟zabbix相关的内容.参考的是zabb ...
- 03: zabbix API接口 对 主机、主机组、模板、应用集、监控项、触发器等增删改查
目录:Django其他篇 01: 安装zabbix server 02:zabbix-agent安装配置 及 web界面管理 03: zabbix API接口 对 主机.主机组.模板.应用集.监控项. ...
- python 全栈开发,Day124(MongoDB初识,增删改查操作,数据类型,$关键字以及$修改器,"$"的奇妙用法,Array Object 的特殊操作,选取跳过排序,客户端操作)
一.MongoDB初识 什么是MongoDB MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介 ...
- Mybatis学习总结(二)—使用接口实现数据的增删改查
在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num ...
- 利用API方式进行数据库的增删改查
/* 将数据库的增删改查单独放进一个包 */ package com.itheima28.sqlitedemo.dao; import java.util.ArrayList; import java ...
- 在python中连接mysql数据库,并进行增删改查
数据库在开发过程中是最常见的,基本上在服务端的编程过程中都会使用到,mysql是较常见的一种数据库,这里介绍python如果连接到数据库中,并对数据库进行增删改查. 安装mysql的python扩展 ...
- Python Web实战:Python+Django+MySQL实现基于Web版的增删改查
前言 本篇使用Python Web框架Django连接和操作MySQL数据库学生信息管理系统(SMS),主要包含对学生信息增删改查功能,旨在快速入门Python Web,少走弯路.效果演示在项目实战最 ...
随机推荐
- Binder机制
在Android系统的Binder机制中,由一系统组件组成,分别是Client.Server.Service Manager和Binder驱动程序,其中Client.Server和Service Ma ...
- <Stackoverflow> 如何提问
如何提问 欢迎来到Stack Overflow! 我们很乐意帮助你,但是实际情况是并非每一个问题都能得到解决.为了提高你的机会,这儿有一些帮助: 1 检索及调查 在提出你的问题之前,你已经通过检索来寻 ...
- 关于python的import
在软件包里,必须添加__init__.py文件. 想要对外公开的module必须在__init__.py内import一次,这样这些module才能被外部代码import并调用.
- 通过实例让你真正明白mapreduce---填空式、分布(分割)编程
本文链接:http://www.aboutyun.com/thread-8303-1-1.html 问题导读: 1.如何在讲mapreduce函数中的字符串等信息,输出到eclipse控制台?2.除了 ...
- 取消本地SVN文件夹与服务器关联
问题:之前建了一个SVN代码库,同步了代码上去,但中途发现建库时的规则搞错了,就把服务器上的库给删了重建,然后改变本地代码的svn服务器关联地址,但使用Relocate一直报错. 错误有两种情况:1. ...
- 第三百零七天 how can I 坚持
快放假了,上班也没啥事,感觉也挺累的.明天基本都走了,收拾收拾,准备明天出发.电脑就不带了. 和她聊的还可以,小样,还想当老师,别离开济南就行,我的未来在哪里啊. 晚上炒了白菜,下了乌冬面,明天上午晚 ...
- 问题-Delphi2007跟踪变量时提示“E2171 Variable 'APolygon' inaccessible here due to optimization”
问题现象:Delphi2007跟踪变量时提示“E2171 Variable 'APolygon' inaccessible here due to optimization” . 问题原因:可能是因为 ...
- 短信验证倒计时60s
$("#zphone").click(function(){ var tel2 = $("#regTel").val(); if(flag.tel){ $.po ...
- UVa540 Team Queue
// 题意:有t个团队的人在排队.每次来了一个新人之后,如果他有队友在排队,那么这个新人会插队到队友的身后. // 要求支持三种指令:ENQUEUE x; DEQUEUE(队首出队); STOP.模拟 ...
- Kerberos和NTLM - SQL Server
当我们使用Windows Authentication去连接SQL Server的时候,SQL Server可能会使用Kerberos或者是NTLM来进行认证,有时间就会因为认证失败的缘故造成各种登录 ...