- python环境配置
yum -y install python-pip
安装argparse模块
pip install -i https://pypi.douban.com/simple/ argparse - 脚本修改
请修改脚本中zabbix登录地址以及zabbix管理员帐户及密码#!/usr/bin/env python
#-*- coding: utf-8 -*- import json
import sys
import urllib2
import argparse from urllib2 import URLError reload(sys)
sys.setdefaultencoding('utf-8') class zabbix_api:
def __init__(self):
self.url = 'http://zab.test.com/api_jsonrpc.php'
self.header = {"Content-Type":"application/json"} def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "admin",
"password": "zabbix"
},
"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 "\033[041m 认证失败,请检查URL !\033[0m",e.code
except KeyError as e:
print "\033[041m 认证失败,请检查用户名密码 !\033[0m",e
else:
response = json.loads(result.read())
result.close()
#print response['result']
self.authID = response['result']
return self.authID def hostid_get_hostname(self, hostId=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter": {"hostid": hostId}
},
"auth": self.user_login(),
"id": 1
})
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
else:
response = json.loads(result.read())
#print response
result.close() if not len(response['result']):
print "hostId is not exist"
return False #print "主机数量: \33[31m%s\33[0m" % (len(response['result']))
host_dict=dict()
for host in response['result']:
status = {"": "OK", "": "Disabled"}
available = {"": "Unknown", "": "available", "": "Unavailable"}
#if len(hostId) == 0:
# print "HostID : %s\t HostName : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m" % (
# host['hostid'], host['name'], status[host['status']], available[host['available']])
#else:
# print "HostID : %s\t HostName : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m" % (
# host['hostid'], host['name'], status[host['status']], available[host['available']])
host_dict['name']=host['name']
host_dict['status']=status[host['status']]
host_dict['available']=available[host['available']]
return host_dict def hostid_get_hostip(self, hostId=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostinterface.get",
"params": {
"output": "extend",
"filter": {"hostid": hostId}
},
"auth": self.user_login(),
"id": 1
})
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
else:
response = json.loads(result.read())
# print response
result.close() if not len(response['result']):
print "\033[041m hostid \033[0m is not exist"
return False #print "主机数量: \33[31m%s\33[0m" % (len(response['result']))
for hostip in response['result']:
#print hostip
#if len(hostip) == 0:
# print "HostID : %s\t HostIp : %s \t Port : %s " % (hostip['hostid'], hostip['ip'], hostip['port'])
#else:
# print "HostID : %s\t HostIp :\33[32m%s\33[0m \t Port :\33[31m%s\33[0m" % (
# hostip['hostid'], hostip['ip'], hostip['port'])
return hostip['ip'] def host_get(self,hostName=''):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
#"filter":{"host":""}
"filter":{"host":hostName}
},
"auth": self.user_login(),
"id": 1
})
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
else:
response = json.loads(result.read())
#print reqponse
result.close() if not len(response['result']):
print "\033[041m %s \033[0m is not exist" % hostName
return False print "主机数量: \033[31m%s\033[0m"%(len(response['result']))
for host in response['result']:
status={"":"OK","":"Disabled"}
available={"":"Unknown","":"available","":"Unavailable"}
#print host
if len(hostName)==0:
print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :%s \t Available :%s"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])
else:
print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']])
return host['hostid'] def hostip_get(self, hostIp=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostinterface.get",
"params": {
"output": "extend",
"filter": {"ip": hostIp}
},
"auth": self.user_login(),
"id": 1
})
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
else:
response = json.loads(result.read())
# print response
result.close() if not len(response['result']):
print "\033[041m hostip \033[0m is not exist"
return False print "主机数量: \33[31m%s\33[0m" % (len(response['result']))
for hostip in response['result']:
host = self.hostid_get_hostname(hostip['hostid'])
if len(hostip) == 0:
print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m"%(hostip['hostid'],host['name'],hostip['ip'],host['status'],host['available'])
else:
print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\33[32m%s\33[0m \t Available :\33[31m%s\33[0m"%(hostip['hostid'],host['name'],hostip['ip'],host['status'],host['available'])
return hostip['hostid'] def hostgroup_get(self, hostgroupName=''):
data = json.dumps({
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params":{
"output": "extend",
"filter": {
"name": hostgroupName
}
},
"auth":self.user_login(),
"id":1,
}) 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 "Error as ", e
else:
# result.read()
response = json.loads(result.read())
result.close()
#print response()
if not len(response['result']):
print "\033[041m %s \033[0m is not exist" % hostgroupName
return False for group in response['result']:
if len(hostgroupName)==0:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
else:
print "hostgroup: \033[31m%s\033[0m\tgroupid : %s" %(group['name'],group['groupid'])
self.hostgroupID = group['groupid']
return group['groupid'] def template_get(self,templateName=''):
data = json.dumps({
"jsonrpc":"2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"name":templateName
}
},
"auth":self.user_login(),
"id":1,
}) 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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
#print response
if not len(response['result']):
print "\033[041m %s \033[0m is not exist" % templateName
return False for template in response['result']:
if len(templateName)==0:
print "template : %s \t id : %s" % (template['name'], template['templateid'])
else:
self.templateID = response['result'][0]['templateid']
print "Template Name :%s"%templateName
return response['result'][0]['templateid'] def hostgroup_create(self,hostgroupName):
if self.hostgroup_get(hostgroupName):
print "hostgroup \033[42m%s\033[0m is exist !" % hostgroupName
sys.exit(1) data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostgroupName
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "添加主机组:%s hostgroupID : %s"%(hostgroupName,self.hostgroup_get(hostgroupName)) def host_create(self, hostIp, hostgroupName, templateName, hostName):
if self.host_get(hostName) or self.hostip_get(hostIp):
print "该主机已经添加!"
sys.exit(1) group_list=[]
template_list=[]
for i in hostgroupName.split(','):
var = {}
var['groupid'] = self.hostgroup_get(i)
group_list.append(var)
for i in templateName.split(','):
var={}
var['templateid']=self.template_get(i)
template_list.append(var) data = json.dumps({
"jsonrpc":"2.0",
"method":"host.create",
"params":{
"host": hostName,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": hostIp,
"dns": "",
"port": ""
}
],
"groups": group_list,
"templates": template_list,
},
"auth": self.user_login(),
"id":1
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
response = json.loads(result.read())
result.close()
print "add host : %s id :%s" % (hostIp, hostName)
except URLError as e:
print "Error as ", e
except KeyError as e:
print "\033[041m 主机添加有误,请检查模板正确性或主机是否添加重复 !\033[0m",e
print response def host_disable(self,hostip):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": self.host_get(hostip),
"status": 1
},
"auth": self.user_login(),
"id": 1
})
request = urllib2.Request(self.url,data)
#opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(TerminalPassword()))
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
#result = opener.open(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
print '------------主机现在状态------------'
print self.host_get(hostip) def host_enable(self,hostip):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": self.host_get(hostip),
"status": 0
},
"auth": self.user_login(),
"id": 1
})
request = urllib2.Request(self.url,data)
for key in self.header:
request.add_header(key, self.header[key])
try:
result = urllib2.urlopen(request)
#result = opener.open(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
print '------------主机现在状态------------'
print self.host_get(hostip) def host_delete(self,hostNames):
hostid_list=[]
for hostName in hostNames.split(','):
hostid = self.host_get(hostName=hostName)
if not hostid:
print "主机 \033[041m %s\033[0m 删除失败 !" % hostName
sys.exit()
hostid_list.append(hostid) data=json.dumps({
"jsonrpc": "2.0",
"method": "host.delete",
"params": hostid_list,
"auth": self.user_login(),
"id": 1
}) request = urllib2.Request(self.url,data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
result.close()
print "主机 \033[041m %s\033[0m 已经删除 !" % hostName
except Exception,e:
print e if __name__ == "__main__":
zabbix=zabbix_api()
parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
parser.add_argument('-C','--add-host',dest='addhost',nargs=4,metavar=('192.168.2.1', 'groupname', 'Template01,Template02', 'hostName'),help='添加主机,多个主机组或模板用逗号')
parser.add_argument('-d','--disable',dest='disablehost',nargs='+',metavar=('sh-aa-01'),help='禁用主机,填主机名')
parser.add_argument('-e','--enable',dest='enablehost',nargs='+',metavar=('sh-aa-01'),help='开启主机,填主机名')
parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('sh-aa-01'),help='删除主机,填主机名')
parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0') if len(sys.argv) == 1:
print parser.print_help()
#print zabbix.host_get(hostName='bbb')
#print zabbix.hostip_get(hostIp='127.0.0.1')
#print zabbix.hostid_get_hostname(hostId='10108')
#print zabbix.hostid_get_hostid(hostId='10105')
#print zabbix.hostgroup_get(hostgroupName='Linux servers')
#print zabbix.hostgroup_get(hostgroupName='aaa')
#print zabbix.host_delete('hz-aaa-02')
else:
args = parser.parse_args()
if args.listhost != 'host':
if args.listhost:
zabbix.host_get(args.listhost)
else:
zabbix.host_get()
if args.listgroup != 'group':
if args.listgroup:
zabbix.hostgroup_get(args.listgroup)
else:
zabbix.hostgroup_get()
if args.listtemp != 'template':
if args.listtemp:
zabbix.template_get(args.listtemp)
else:
zabbix.template_get()
if args.addgroup:
zabbix.hostgroup_create(args.addgroup[0])
if args.addhost:
zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2], args.addhost[3])
if args.disablehost:
zabbix.host_disable(args.disablehost)
if args.enablehost:
zabbix.host_enable(args.enablehost)
if args.deletehost:
zabbix.host_delete(args.deletehost[0])zbx_tools.py
(原文地址:https://www.jianshu.com/p/e087cace8ddf)
使用方法
帮助说明
python zbx_tools.py
查询主机
python zbx_tools.py -H
查询主机组
python zbx_tools.py -G
查询模板信息
python zbx_tools.py -T | grep Linux
添加主机组
python zbx_tools.py -A ADDGROUP
添加主机
python zbx_tools.py -C 10.10.40.20 "Linux servers" "Template OS Linux" "HostName_Test"
python zbx_tools.py -C 10.10.40.20 "Linux servers","Discovered hosts" "Template OS Linux","Template App HTTP Service" "HostName_Test"
禁用主机
python zbx_tools.py -d "HostName_Test"
开启主机
python zbx_tools.py -e "HostName_Test"
删除主机
python zbx_tools.py -D "HostName_Test"
利用zabbix api添加、删除、禁用主机的更多相关文章
-
利用zabbix API 统计一段时间内监控项的均值和峰值
#coding:utf-8 #给定主机IP获取一段时间内cpu的均值和峰值并写入文件(txt,可以跑完后直接把后缀名改为csv以表格形式打开):需要指定IP文件 import requests imp ...
-
Python调用zabbix API批量添加主机 (读取Excel)
本文转载自:http://blog.mreald.com/178 Zabbix可以通过自发现添加主机,不过有时候不准确,通过API添加会更加准确! 脚本使用的跟zabbix相关的内容.参考的是zabb ...
-
python3 调用zabbix API实现批量增加删除主机,主机各种监控项------实战
在以前的博客中谈到了利用zabbix接口来对主机进行批量的增删改查 这里在不用环境中实战遇到了不同问题,这里记录下来以便后续review 以下为实战中获取token的代码,在zabbix标准接口文档中 ...
-
03: zabbix API接口 对 主机、主机组、模板、应用集、监控项、触发器等增删改查
目录:Django其他篇 01: 安装zabbix server 02:zabbix-agent安装配置 及 web界面管理 03: zabbix API接口 对 主机.主机组.模板.应用集.监控项. ...
-
python 调用zabbix api接口实现主机的增删改查
python程序调用zabbix系统的api接口实现对zabbix_server端主机的增删改查,使用相关功能时候,需要打开脚本中的相关函数. 函数说明: zabbixtools() 调用zabbi ...
-
LNMP添加、删除虚拟主机及伪静态使用教程
一般情况下每个虚拟主机就是一个网站,网站一般通过域名进行访问.LNMP 1.2的网站添加过程和LNMP 1.1的基本类似,但是增加了FTP和数据库的创建.LNMP1.2的防跨目录也由原来在php.in ...
-
百度地图API示例之添加/删除工具条、比例尺控件
代码 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" cont ...
-
利用Dnspod api批量更新添加DNS解析【python脚本】 - 推酷
利用Dnspod api批量更新添加DNS解析[python脚本] - 推酷 undefined
-
PHP通过ZABBIX API获取主机信息 VS 直接从数据库获取主机信息
最近项目需要获取linux主机的一些信息,如CPU使用率,内存使用情况等.由于我们本身就装了zabbix系统,所以我只用知道如何获取信息即可,总结有两种方法可以获取. 一.通过ZABBIX API获取 ...
随机推荐
-
Java实现的二分查找算法
二分查找又称折半查找,它是一种效率较高的查找方法. 折半查找的算法思想是将数列按有序化(递增或递减)排列,查找过程中采用跳跃式方式查找,即先以有序数列的中点位置为比较对象,如果要找的元素值小 于该中点 ...
-
bzoj1058: [ZJOI2007]报表统计
set.操作:insert(u,v)在u后面插入v,若u后面已插入过,在插入过的后面插入.mingap求出序列两两之间差值的最小值.minsortgap求出排序后的序列两两之间的最小值.用multis ...
-
Android 混淆文件project.properties和proguard-project.txt
参考文档:http://blog.csdn.net/xueyepiaoling/article/details/8202359 http://glblong.blog.51cto.com/305861 ...
-
Flink资料(5) -- Job和调度
该文档翻译自Jobs and Scheduling ----------------------------------------------- 该文档简单描述了Flink是如何调度Job的,以及如 ...
-
JavaScript实现上传图片预览[js前端实现]
<body> <input type="file" id="file_input" onchange="show_image()&q ...
-
Java多线程学习(二)---线程创建方式
线程创建方式 摘要: 1. 通过继承Thread类来创建并启动多线程的方式 2. 通过实现Runnable接口来创建并启动线程的方式 3. 通过实现Callable接口来创建并启动线程的方式 4. 总 ...
-
windows cmd下ssh连接免密码问题解决
windows 7 cmd下 ssh -T username@serverip 免密码连接成功 有的同学在windows下开发,并且在windows下安装了git for windows,这些资源已经 ...
-
vue中的js引入图片,必须require进来
需求:如何components里面的index.vue怎样能把assets里面的图片拿出来. 1.在img标签里面直接写上路径: <img src="../assets/a1.png& ...
-
c++向量
https://blog.csdn.net/suxiao_shaoer/article/details/52180087 vector(向量): C++中的一种数据结构,确切的说是一个类.它相当于一个 ...
-
OpenMPI源码剖析:网络通信原理(一)
MPI中的网络通信的原理,需要解决以下几个问题: 1. MPI使用什么网络协议进行通信? 2.*数据库是存储在哪一台机器上? 3.集群中如果有一台机器挂掉了是否会影响其他机器? 参考: https: ...