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,少走弯路.效果演示在项目实战最 ...
随机推荐
- HDU5742:It's All In The Mind(模拟+贪心 )
题意: 给出n和m,表示n个数,之后会给出m个下标xi和值yi,a[xi]=yi,n个数是不下降的,且总和>0,要使得(x1+x2)/∑(xi)最大. 分析: 尽可能使得前两个数最大,其他数尽可 ...
- emacs资源
当clone github时若连接不上,可以使用http代理,形如:export http_proxy=61.172.249.94:80一年成为emacs高手: https://github ...
- 解决oracle启动的错误: ORA-00119 ORA-00132
$ sqlplus / as sysdbaSQL>create pfile fromspfile修改$ORACLE_HOME/dbs下的文件initDEV.ora中的*.local_listen ...
- Hibernate关联关系之——单向n-1
1 .单向 n-1 关联只需从n的一端可以访问1的一端 2.域模型: 从Order到Customer的多对一单向关联需要在Order类中定义一个Customer属性,而在Customer类中无需定义存 ...
- JavaSE聊天室
今天学习了一下简单聊天程序(类似QQ那种)的编写过程,从最初的0.1版本到最后的1.3版本,功能不断地增强,下面对一天的学习内容进行梳理. 版本0.1 我们的需求是显示一个窗体,其他什么也不用做,其他 ...
- JavaIO(04)字符流--Writer and Reader
字符流: 常识:在java中一个字符等于两个字节: 操作字符流的两个类:Writer,Reader API文档介绍(Writer): public abstract class Write ...
- UIImageView旋转任意角度---实现方法
转自:http://blog.csdn.net/trandy/article/details/6626281 -(UIImageView *) makeRotation:(UIImageView *) ...
- input type=“submit”屏蔽自带的提交事件
<p><input type="submit" class="submit" value="确认支付" onclick=& ...
- rqnoj-396-SY学语文-dp
纯动态规划. 注意初始化为-INF #include<stdio.h> #include<algorithm> #include<iostream> #includ ...
- python求3的倍数与和
suqares=[] i=1 sum=0 while i<=100: i+=1 if i*3: sum=sum+i # print(i) suqares.append(i*3) # print( ...