zabbix批量操作
利用zabbix-api来实现zabbix的主机的批量添加,主机的查找,删除等等操作。
代码如下:
#!/usr/bin/env python
#-*- coding: utf- -*- 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 #self.url = 'http://zabbix.weimob.com/api_jsonrpc.php'
self.url = 'http://zb.qeeyou.cn:81/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": "zp1@663400"
},
"id":
}) 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":
})
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 proxy_get(self):
data=json.dumps({
"jsonrpc": "2.0",
"method": "proxy.get",
"params": {
"output": "extend",
"selectInterfaces": "extend",
"selectHosts": "extend"
},
"auth": self.user_login(),
"id":
})
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
for i in range(len(response['result'])):
for j in range(len(response['result'][i]['hosts'])):
r=response['result'][i]['hosts'][j]
#print r
print " proxy_host: %s\t proxy_ID: %s \thost: %s\t hostid: %s" %(response['result'][i]['host'],response['result'][i]['proxyid'],r['host'],r['hostid'])
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":
})
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":
})
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)==:
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":
})
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) == :
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":,
}) 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)==:
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":,
}) 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)==:
print "template : %s \t id : %s" % (template['name'], template['templateid'])
else:
self.templateID = response['result'][]['templateid']
print "Template Name :%s"%templateName
return response['result'][]['templateid'] def hostgroup_create(self,hostgroupName):
if self.hostgroup_get(hostgroupName):
print "hostgroup \033[42m%s\033[0m is exist !" % hostgroupName
sys.exit() data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostgroupName
},
"auth": self.user_login(),
"id":
})
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() 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": ,
"main": ,
"useip": ,
"ip": hostIp,
"dns": "",
"port": ""
}
],
"groups": group_list,
"templates": template_list,
},
"auth": self.user_login(),
"id":
})
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":
},
"auth": self.user_login(),
"id":
})
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":
},
"auth": self.user_login(),
"id":
})
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":
}) 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=,dest='addgroup',help='添加主机组')
parser.add_argument('-C','--add-host',dest='addhost',nargs=,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) == :
#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='')
#print zabbix.hostid_get_hostid(hostId='')
#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[])
if args.addhost:
zabbix.host_create(args.addhost[], args.addhost[], args.addhost[], args.addhost[])
if args.disablehost:
zabbix.host_disable(args.disablehost)
if args.deletehost:
zabbix.host_delete(args.deletehost[])
zbx_tool.py
#!/usr/bin/env python
#-*- coding: utf- -*- #!/usr/bin/env python
#-*- coding: utf- -*- import os
import sys
import argparse # 导入zabbix_tool.py的zabbix_api类
from zbx_tool import zabbix_api
import subprocess
hostfile=dict()
reload(sys)
sys.setdefaultencoding('utf-8') host_file = 'target'
#base_templates = ""
cmd = 'python zbx_tool.py' # 实例化zabbix_api
zabbix=zabbix_api()
def open_file():
with open ('/etc/ansible/zhangdianke/zabbix/Tengxunode.txt','rb') as f:
for ip in f.readlines():
getHostName(ip.strip())
def getHostName(ip):
a="ansible "
b=ip
c=" -i /etc/ansible/zhangdianke/zabbix/tengxunode.txt -m shell -a 'cat /etc/myshell/new_baseinfo |grep hostname'|awk -F ' = ' {'print $2'}|sed -n 2p"
command=a+b+c
subp=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE)
#with open("gethost.txt",'a+')as f:
#hostfile=dict()
for line in subp.stdout.readlines():
hostfile[line.rstrip('\n')]=ip
def create_hosts():
groups = raw_input("Please Input Group Name: ")
add_templates = raw_input("Please Input Template Name: ")
templates = add_templates
cmd1 = cmd + ' -A ' + groups #python zbx_tool.py -A groupname
os.system(cmd1) for key in hostfile:
cmd2 = cmd + ' --add-host ' + hostfile[key] + ' ' + groups + ' ' +templates + ' ' + key
os.system(cmd2) def get_hosts():
with open(host_file) as fb:
[zabbix.host_get(line.strip()) for line in fb]
def get_hostip():
with open(host_file) as fb:
[zabbix.hostip_get(line.strip()) for line in fb]
def delete_hosts():
with open(host_file) as fb:
[zabbix.host_delete(line.strip()) for line in fb] def enable_hosts():
with open(host_file) as fb:
[zabbix.host_enablee(line.strip()) for line in fb] def disable_hosts():
with open(host_file) as fb:
[zabbix.host_disable(line.strip()) for line in fb]
def proxy_get_hosts():
zabbix.proxy_get() if __name__ == "__main__":
#with open ('/etc/ansible/zhangdianke/zabbix/Tengxunode.txt','rb') as f:
# for ip in f.readlines():
#i=str(i)
# print ip
# getHostName(ip.strip())
if len(sys.argv) == or sys.argv[] == '-h':
print "you need a argv,like:"
print """
python zbx_cli.py -A #批量添加主机,请确保每台主机22端口开放
python zbx_cli.py -B #得到所有代理的主机信息
python zbx_cli.py -C #批量查询主机,确保target文件格式正确
python zbx_cli.py -D #批量删除主机,确保target文件格式正确
python zbx_cli.py -e #批量开启主机,确保target文件格式正确
python zbx_cli.py -d #批量禁止主机,确保target文件格式正确
"""
else:
if sys.argv[] == '-A':
open_file()
create_hosts()
elif sys.argv[] == '-B':
proxy_get_hosts()
elif sys.argv[] == '-C':
get_hosts()
elif sys.argv[] == '-D':
delete_hosts()
elif sys.argv[] == '-e':
disable_hosts()
elif sys.argv[] == '-d':
enable_hosts()
zbx_cli
求某个组的总流量grpsum["VIP-XM-B","net.if.in[eth0]",last,0]
zabbix批量操作的更多相关文章
- python调用zabbix接口实现Action配置
要写这篇博客其实我的内心是纠结的,老实说,我对zabbix的了解实在不多.但新公司的需求不容置疑,当我顶着有两个头大的脑袋懵懵转入运维领域时,面前摆着两百多组.上千台机器等着写入zabbix监控的需求 ...
- zabbix 批量生成聚合图形
通过插入数据库的方式批量生成 zabbix 聚合图形 原型图形 聚合的 sql 批量操作 .在聚合图形创建好一个聚合图形A.找出图形A的ID (创建图形的时候记得填写好行数和列数) select sc ...
- 通过zabbix自带api进行主机的批量添加操作
通过zabbix自带api进行批量添加主机 我们需要监控一台服务器的时候,当客户端装好zabbix-agent端并正确配置以后,需要在zabbix-server的web gui界面进行添加zabbix ...
- 使用API接口在zabbix系统中登陆、创建、删除agent
一.API的介绍 API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力 ...
- Zabbix二次开发_01基础
最近有个想法:想做一个zabbix数据的二次呈现,所以来写一下Zabbix的api的内容. 先说下zabbix api的认证基础. Zabbix API简介 Zabbix API开始扮演着越来越重要的 ...
- ZABBIX API简介及使用
API简介 Zabbix API开始扮演着越来越重要的角色,尤其是在集成第三方软件和自动化日常任务时.很难想象管理数千台服务器而没有自动化是多么的困难.Zabbix API为批量操作.第三方软件集成以 ...
- Zabbix概术及基础介绍(一)
一.Zabbix介绍 Zabbix 是由Alexei Vladishev创建,目前由Zabbix SIA在持续开发和支持.Zabbix 是一个企业级的分布式开源监控方案.Zabbix是一款能够监控各种 ...
- Zabbix监控详解
Zabbix是什么 Zabbix 是由Alexei Vladishev创建,目前由Zabbix SIA在持续开发和支持. Zabbix 是一个企业级的分布式开源监控方案. Zabbix是一款能够监控各 ...
- Zabbix之CentOS7.3下yum安装Zabbix3.5
Zabbix特点介绍 (此介绍来源于https://www.zabbix.com/documentation/3.4/zh/manual/introduction/features) 概述Zabbix ...
随机推荐
- 01 Django REST Framework 介绍
01-Django REST Framework的介绍 Django REST框架是一个用于构建Web API的强大而灵活的工具包. 您可能希望使用REST框架的一些原因: 1. Web可浏览API对 ...
- 2019年DNS服务器速度排行榜
第一名:DNSPod 不得不说腾讯自从收购了DNSPod后,无论是服务还是速度都有显著的提升,无论是访问速度还是解析速度都在国内是处于龙头大哥的地位,昔日的老大114的地位已经不保,作为腾讯旗下的公司 ...
- matplotlib 入门之Pyplot tutorial
文章目录 pyplot 介绍 修饰你的图案 格式字符串 [color][marker][line] Colors Markers Line Styles 利用关键字作图(大概是数据映射到属性吧) 传入 ...
- 用HttpClient和用HttpURLConnection做爬虫发现爬取的代码少了的问题
最近在学习用java来做爬虫但是发现不管用那种方式都是爬取的代码比网页的源码少了很多在网上查了很多都说是inputStream的缓冲区太小而爬取的网页太大导致读取出来的网页代码不完整,但是后面发现并不 ...
- 爬虫——scrapy框架
Scrapy是一个异步处理框架,是纯Python实现的爬虫框架,其架构清晰,模块之间的耦合程度低,可拓展性强,可以灵活完成各种需求.我们只需要定制几个模块就可以轻松实现一个爬虫. 1.架构 Scra ...
- 简单封装mongodb
首先安装mongodb npm i mongodb --save 简单封装,在modules目录下新建db.js var MongoClient=require('mongodb').MongoCl ...
- asp.net mvc Dateset读取Excel数据
//处理Excel //读取Excel [NonAction] public static DataSet ExcelToDS(string Path) { //根据情况选择合适的连接字符,参考msd ...
- Pycharm中怎么给字典中的多个键-值对同时加上单引号
今天看了个爬虫视频,崔庆才讲师的免费视频, 里面一个批量给header加引号2s完成,这波操作让我眼前一亮. 最终还是发现了骚操作的背后手速是真的快. pycharm中按ctrl+r 勾选右上角的Re ...
- Oracle 序列(sequence)
序列(sequence) 是Oracle提供的用于生成一系列唯一数字的数据库对象.它会自动生成顺序递增或者递减的序列号,以实现自动提供唯一的主键值.序列可以在多用户并发环境中使用,并且可以为所有用户生 ...
- [转帖]分布式Unique ID的生成方法一览
分布式Unique ID的生成方法一览 http://www.importnew.com/22211.html 分布式的Unique ID的用途如此广泛,从业务对象Id到日志的TraceId,本文总结 ...