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 ...
随机推荐
- 面试(一)-HashMap
一.前言 其实这一面来的挺突然,也是意想不到的,这个要起源于BOSS直聘,很巧,其实也算是一种缘分吧,谢谢BOSS那个哥们,还是那句话来滨江我请你吃饭,身怀感激你总会遇到帮助你的人,只是这 ...
- .NET Core Community 第二个千星项目诞生:Util
本文所有打赏将全数捐赠于 NCC(NCC 的资金目前由 倾竹大人 负责管理),请注明捐赠于 NCC.捐赠情况将由倾竹大人另行公示. 项目简介 作为一款旨在提升小型团队开发输出能力.提高团队效率.降低项 ...
- Linux Namespace : UTS
UTS namespace 用来隔离系统的 hostname 以及 NIS domain name.UTS 据称是 UNIX Time-sharing System 的缩写. hostname 与 N ...
- 用asp.net core 把用户访问记录优化到极致
菜菜呀,前几天做的用户空间,用户反映有时候比较慢呀 CEO,CTO,CFO于一身的CXO 是吗? 菜菜 我把你拉进用户反馈群,你解决一下呀 CEO,CTO,CFO于一身的CXO (完了,以后没清净时候 ...
- zabbix安装与配置
一.什么是zabbix及优缺点(对比cacti和nagios) Zabbix能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制以让系统管理员快速定位/解决存在的各种问题.是一个基于WE ...
- Python-爬虫的基本原理
什么是爬虫 爬虫就是请求网站并提取数据的自动化程序.其中请求,提取,自动化是爬虫的关键!下面我们分析爬虫的基本流程 爬虫的基本流程 发起请求通过HTTP库向目标站点发起请求,也就是发送一个Reques ...
- Python_每日习题_0003_完全平方数
# 题目 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? # 程序分析 因为168对于指数爆炸来说实在太小了,所以可以直接省略数学分析,用最朴素的方法来获取 ...
- c++入门之详细探讨类的一些行为
之前我们讨论过类成员的组成,尤其是成员函数,我们知道了定义一个类的时候,我们往往定义了:构造函数,析构函数,其他函数,以及友元函数(友元函数不是必须的). 同时,我们知道了这样一个事情:在定义一个对象 ...
- 11-vue的使用
一.安装 对于新手来说,强烈建议大家使用<script>引入 二. 引入vue.js文件 我们能发现,引入vue.js文件之后,Vue被注册为一个全局的变量,它是一个构造函数. 三.使用V ...
- nginx强制使用https访问(http跳转到https)
Nginx 的 Location 从零开始配置 - 市民 - SegmentFault 思否https://segmentfault.com/a/1190000009651161 nginx配置loc ...