zabbix常用的python类api
zabbix自带api
#!/usr/bin/python
#coding:utf-8 import requests
import json url = "http://192.168.99.14/zabbix/api_jsonrpc.php"
headers = {"Content-Type": "application/json-rpc"} def login_zabbix():
data = {
"jsonrpc":"2.0",
"method":"user.login",
"id":1,
"auth":None,
"params": {
"user": "Admin",
"password": "zabbix"
}
} r = requests.post(url, data = json.dumps(data), headers = headers) _content = json.loads(r.content)
return _content['result'] def create_hostgoup():
_auth = login_zabbix()
data = {
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": "reboot"
},
"auth": _auth,
"id": 1
} r = requests.post(url, data=json.dumps(data), headers=headers)
_content = json.loads(r.content)
print _content def get_goupid():
_auth = login_zabbix()
data = {
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": [
"reboot"
]
}
},
"auth": _auth,
"id": 1
}
r = requests.post(url, data=json.dumps(data), headers=headers)
_content = json.loads(r.content)
return _content['result'][0]['groupid'] def get_templateid():
_auth = login_zabbix()
data = {
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"host": [
"Template OS Linux",
]
}
},
"auth": _auth,
"id": 1
}
r = requests.post(url, data=json.dumps(data), headers=headers)
_content = json.loads(r.content)
return _content['result'][0]['templateid'] def create_host(_host_list):
_auth = login_zabbix()
_groupid = get_goupid()
_templdateid = get_templateid() for _host in _host_list:
data = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": _host['host'],
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": _host['ip'],
"dns": "",
"port": ""
}
],
"groups": [
{
"groupid": _groupid
}
],
"templates": [
{
"templateid": _templdateid
}
],
"inventory_mode": 0,
"inventory": {
"macaddress_a": "",
"macaddress_b": ""
}
},
"auth": _auth,
"id": 1
}
r = requests.post(url, data=json.dumps(data), headers=headers)
_content = json.loads(r.content)
print _content['result']['hostids'] if __name__ == "__main__":
_host_list = [
{"ip": "192.168.99.10", "host": "reboot-devops-02"},
{"ip": "192.168.99.11", "host": "reboot-ms-web-01"},
{"ip": "192.168.99.12", "host": "reboot-ms-web-02"},
{"ip": "192.168.99.13", "host": "reboot-ms-web-03"}
]
create_host(_host_list)
第三方插件
#!/usr/bin/python
# coding:utf-8
from flask import current_app
from zabbix_client import ZabbixServerProxy
from app.models import Zbhost, Server
from app import db class Zabbix(object):
def __init__(self):
self.url = current_app.config.get('ZABBIX_API_URL')
self.username = current_app.config.get('ZABBIX_API_USER')
self.password = current_app.config.get('ZABBIX_API_PASS')
self._login() def _login(self):
self.zb = ZabbixServerProxy(self.url)
self.zb.user.login(user=self.username, password=self.password) def __del__(self):
self.zb.user.logout() def get_hostgroup(self):
return self.zb.hostgroup.get(output=['groupid', 'name']) def _create_host(self, params):
try:
return self.zb.host.create(**params)
except Exception,e:
return e.args def create_zb_host(self, hostname, ip, groupid = 2):
"""
创建zabbix监控主机
:param hostname:
:param ip:
:param groupid:
:return:
"""
data = {"host": hostname,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": ip,
"dns": "",
"port": ""
}
],
"groups": [
{
"groupid": groupid
}
]
}
return self._create_host(data) def get_hosts(self):
return self.zb.host.get(output=["hostid", "host"]) def get_interfaces(self, ids):
"""
获取host的ip
:param ids:
:return:
"""
interface = self.zb.hostinterface.get(hostids = ids, output = ["hostid", "ip"])
ret = {}
for _it in interface:
ret[_it['hostid']] = _it['ip']
return ret def get_templates(self, ids):
return self.zb.template.get(hostids = ids, output = ["templateid", "name"]) # 接触模板绑定
def unlink_template(self, hostid, templateid):
templates = [{"templateid" : templateid}]
return self.zb.host.update(hostid = hostid, templates_clear = templates) # 新增模板,就是查出原来有的模板,然后拼接最新的模板,一起更新为当前的模板
def replace_template(self, hostid, templateids):
templates = []
for id in templateids:
templates.append({"templateid":id})
try:
ret = self.zb.host.update(hostid=hostid,templates = templates)
return ret
except Exception as e:
return e.args def rsync_zabbix_to_zbhost():
"""
将zabbix里的host信息同步到zbhost里
:return:
"""
zb = Zabbix()
# 1 从zabbix里取出所有的host信息
zabbix_hosts = zb.get_hosts()
zabbix_hosts_interface = zb.get_interfaces([z['hostid'] for z in zabbix_hosts])
commit = False
for host in zabbix_hosts:
h = db.session.query(Zbhost).filter_by(hostid = host['hostid']).all()
if h:
continue
host['ip'] = zabbix_hosts_interface[host['hostid']]
db.session.add(Zbhost(**host))
commit = True
if commit:
db.session.commit() def rsync_server_to_zbhost():
"""
同步cmdb server的数据到缓存表zbhost
"""
hosts = db.session.query(Zbhost).all()
servers = db.session.query(Server).filter(Server.inner_ip.in_([h.ip for h in hosts])).all() server_info = {}
for s in servers:
server_info[s.inner_ip] = s.id for h in hosts:
if not h.cmdb_hostid:
db.session.query(Zbhost).filter(Zbhost.id == h.id).update({"cmdb_hostid":server_info[h.ip]})
db.session.commit() """
取出zabbix中主机和模板信息
"""
def get_zabbix_data(hosts):
zabbix_data = db.session.query(Zbhost).filter(Zbhost.cmdb_hostid.in_([h['id'] for h in hosts])).all()
zb = Zabbix()
ret = []
for zb_host in zabbix_data:
tmp = {}
tmp["hostname"] = zb_host.host
tmp["templates"] = zb.get_templates(zb_host.hostid)
tmp["hostid"] = zb_host.hostid
ret.append(tmp) return ret # 连接模板
def zabbix_link_template(hostids, templateids):
ret = []
zb = Zabbix()
for hostid in hostids:
linked_template_ids = [t['templateid'] for t in zb.get_templates(hostid)]
linked_template_ids.extend(templateids)
ret.append(zb.replace_template(hostid, linked_template_ids)) return ret
使用zabbix_api批量添加模板的脚本:
template_massadd.py #!/usr/bin/python
#-*- coding:utf8 -*-
import json,sys,argparse
from zabbix_api import ZabbixAPI
server = "http://10.11.0.212/api_jsonrpc.php"
username = "Admin"
password = "zabbix"
zapi = ZabbixAPI(server=server, path="", log_level=0)
zapi.login(username, password) '''
1. 安装zabbix插件 D:\python\zabbix>pip install zabbix-api
2. 使用 zabbix_getallhosts.py 脚本获取主机名,将需要的主机名筛选出来 使用方法:
cmd下:
python template_massadd.py --host="chinasoft_cbs_frontend_web01,chinasoft_cbs_frontend_web02,chinasoft_cbs_backend_web1,chinasoft_cbs_backend_web2,chinasoft_cbs_backend_web3,chinasoft_cbs_backend_web4,web01,web02,chinasoft_store_web01,chinasoft_store_web02,chinasoft_apiser_web01,chinasoft_apiser_web02,chinasoft_payment_web01,chinasoft_payment_web02,chinasoft_platform_web01,chinasoft_platform_web02,chinasoft_platform_web03,chinasoft_platform_web04,chinasoft_apicms_backend_web01,chinasoft_apicms_backend_web02,eus-timed-task01,eus-store-pay01,eus-apiserver-web03,eus-apiserver-web04" --"templates"="Template process rsync"
''' # 获取参数
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", help="host name")
parser.add_argument("-t", "--templates", help="template name")
# 解析所传入的参数
args = parser.parse_args()
if not args.host:
args.host = raw_input('host: ')
if not args.templates:
args.templates = raw_input('templates: ')
return args def get_host_id(host):
get_host_id = zapi.host.get(
{
"output": "hostid",
"filter": {
"host":host.split(",")
}
}
)
host_id = []
host_id.append([I['hostid'] for I in get_host_id])
return host_id[0] def get_templates_id(templates):
templates_id = zapi.template.get(
{
"output": "templateid",
"filter": {
"host":templates.split(",")
}
}
)
return templates_id def template_massadd(template_id,host_id):
template_add = zapi.template.massadd(
{
"templates": template_id,
"hosts": host_id
}
)
return "host add template success" # 程序入口
if __name__ == "__main__":
args = get_args()
print 'args:%s' % args
host_id = get_host_id(args.host)
print 'host_id = %s' % host_id
template_id = get_templates_id(args.templates)
print 'template_id: %s' % template_id
if len(host_id) == len(args.host.split(',')):
if len(template_id) == len(args.templates.split(',')):
print template_massadd(template_id,host_id)
else:
print "template not exist"
else:
print "host not exist" # 用法: # python template_massadd.py --host="chinasoft_apiser_web01,chinasoft_payment_web01" --"templates"="Template process rsync"
# host add template success ###########################
批量获取主机名的脚本 #!/usr/bin/evn python
# coding=utf-8 import requests
import json ZABIX_ROOT = "http://10.11.0.212"
url = ZABIX_ROOT + '/api_jsonrpc.php' # user.login
payload = {
"jsonrpc" : "2.0",
"method" : "user.login",
"params": {
'user': 'Admin',
'password':'zabbix',
},
"auth" : None,
"id" : 0,
}
headers = {'content-type': 'application/json',} req = requests.post(url, json=payload, headers=headers)
auth = req.json() # host.get
#主机显示名 'name'],
# hosts是zabbix.conf文件中配置的主机名
payload = {
"jsonrpc" : "2.0",
"method" : "host.get",
"params": {
'output': [
'hostid',
'host'],
},
"auth" : auth['result'],
"id" : 2,
}
res2 = requests.post(url, data=json.dumps(payload), headers=headers)
res2 = res2.json() # f.write(host['name'] + '\n')
for host in res2['result']:
with open('host.txt', 'a+') as f: f.write(host['host'] + '\n')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-21 19:23:02
# @Author : mihong (mihong@yixia.com)
# @Link : ${link}
# @Version : $Id$ from aliyunsdkcore import client
from aliyunsdkcms.request.v20170301 import QueryMetricListRequest
import sys, json, time, random, redis access_key = '这个你不知道就不知道吧'
access_secret = '这个你不知道就不知道吧'
region_id = 'cn-beijing' def GetRdsId():
key_name = "instanceId"
hosts_list = []
RdsIdList = []
FileName = '/workspace/zabbix/rds_monitor/rds_id.list'
with open(FileName, 'r') as File:
for DBInstanceId in File.readlines():
data_dict = {key_name:DBInstanceId.strip()}
hosts_list.append(data_dict)
RdsIdList = [hosts_list[i:i+50] for i in range(0,len(hosts_list),50)]
return RdsIdList def SetRdsValue(Metric, RdsIdList):
clt = client.AcsClient(access_key, access_secret, region_id)
request = QueryMetricListRequest.QueryMetricListRequest()
request.set_accept_format('json')
request.set_Project('acs_rds_dashboard')
request.set_Metric(Metric)
timestamp_start = int(time.time()-120) * 1000
request.set_StartTime(timestamp_start)
request.set_Dimensions(RdsIdList)
request.set_Period('')
request.set_Length('')
result = clt.do_action(request)
ResValue = json.loads(result)['Datapoints']
return ResValue def GetRdsValue(KeyName): return r.get(KeyName) if __name__ == '__main__': time.sleep(random.randint(1,5)) r = redis.Redis(host='localhost', port=7000, db=0) if sys.argv[1] == 'getAllValue': Metrics = ['CpuUsage','IOPSUsage','MemoryUsage','DiskUsage','ConnectionUsage','DataDelay'] for Metric in Metrics:
for RdsIdList in GetRdsId():
KeyArray = SetRdsValue(Metric, RdsIdList)
for i in KeyArray:
RdsId = i['instanceId']
KeyName = i['instanceId'] + '_' + Metric
RdsKeyValue = r.get(KeyName) try:
KeyValue = round(i['Average'], 2)
except IndexError:
KeyValue = 0 if RdsKeyValue == None:
r.set(KeyName, KeyValue, ex=3600)
print Metric, RdsId, KeyValue, 'New set ok'
continue if KeyValue != 0:
r.set(KeyName, KeyValue, ex=3600)
print Metric, RdsId, KeyValue, 'Update set ok'
else:
print Metric, RdsId, KeyValue, 'Value=0 Update set Fail'
continue if sys.argv[1] == 'getRdsValue':
Metric = sys.argv[2]
RdsId = sys.argv[3]
KeyName = RdsId + '_' + Metric
print GetRdsValue(KeyName)
zabbix常用的python类api的更多相关文章
- Lucene学习入门——核心类API
本文讲解Lucene中,创建索引.搜索等常用到的类API 搜索操作比索引操作重要的多,因为索引文件只被创建一次,却要被搜索多次. 索引过程的核心类: 执行简单的索引过程需要如下几个类:IndexWri ...
- Servlet API遍程常用接口和类
本文主要总结Servlet API遍程常用接口和类 Servlet API http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html ...
- 第8.34节 《Python类中常用的特殊变量和方法》总结
本章介绍了Python类中常用的特殊变量和方法,这些特殊变量和方法都有特殊的用途,是Python强大功能的基石之一,许多功能非常有Python特色.由于Python中一切皆对象,理解这些特殊变量和方法 ...
- 第8章 Python类中常用的特殊变量和方法目录
第8章 Python类中常用的特殊变量和方法 第8.1节 Python类的构造方法__init__深入剖析:语法释义 第8.2节 Python类的__init__方法深入剖析:构造方法案例详解 第8. ...
- Java,面试题,简历,Linux,大数据,常用开发工具类,API文档,电子书,各种思维导图资源,百度网盘资源,BBS论坛系统 ERP管理系统 OA办公自动化管理系统 车辆管理系统 各种后台管理系统
Java,面试题,简历,Linux,大数据,常用开发工具类,API文档,电子书,各种思维导图资源,百度网盘资源BBS论坛系统 ERP管理系统 OA办公自动化管理系统 车辆管理系统 家庭理财系统 各种后 ...
- LightMysql:为方便操作MySQL而封装的Python类
原文链接:http://www.danfengcao.info/python/2015/12/26/lightweight-python-mysql-class.html mysqldb是Python ...
- Android常用的工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils. Prefe ...
- Python类属性详解
在python开发中,我们常常用到python的类,今天就通过实例和大家扒一扒类的属性,一起来看看吧. 类属性 1.类定义后就存在,而且不需要实例化 2.类属性使得相同类的不同实例共同持有相同变量 类 ...
- Android常用的工具类(转)
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...
随机推荐
- 【c++】编译器为我们实现了几个类成员函数?
#include <cassert> #include <complex> #include <iostream> class Empty{}; Empty e; ...
- spring中获取dao或对象中方法的实例化对象
spring中获取dao的中方法的实例化对象: //获取应用上下文对象 ApplicationContext ctx = new ClassPathXmlApplicationContext(&quo ...
- Vertica系列: 自动生成Identity 字段值的方法
参考 https://thisdataguy.com/2015/01/05/vertica-some-uses-of-sequences/ 在 vertica 中有三种定义 identity 字段的方 ...
- C++ WString与String互相转换
std::wstring StringToWString(const std::string& str) { , str.c_str(), -, NULL, ); wchar_t *wide ...
- HashMap中的TreeNode,红黑树源码分析
在看HashMap的源码时候看到了TreeNode.因此需要对其进行一个了解.是一个红黑树.可以百度一下红黑树的数据结构.分析了下源码,还是比较枯燥的 红黑树的性质:本身是一个二叉查找树(所有左节点的 ...
- html页面设置<span>的高度和宽度
<span>标签属于行内元素(inline),所以无法设置高度和宽度:如果需要改变其宽高,就需要将其转变为块体元素(block)或行内块体元素(inle-block): 1 span{di ...
- svn 的truck、tag、 merge
参考文章 : https://blog.csdn.net/keda8997110/article/details/21813035
- require/exports 与 import/export 的区别?
文章作者:寸志链接:https://www.zhihu.com/question/56820346/answer/150724784来源:知乎 遵循的模块化规范不一样 模块化规范:即为 JavaScr ...
- 20165234 《Java程序设计》第十周课下作业
相关知识点的总结 泛型 Java 泛型的主要目的是可以建立具有类型安全的集合框架,如链表.散列映射等数据结构. 可以使用“class 名称<泛型列表>”声明一个类,为了和普通的类有所区别, ...
- MySQL触发器trigger的使用
https://www.cnblogs.com/geaozhang/p/6819648.html 触发器的触发 语句的错误 和 触发器里面 错误 都不会运行 NEW与OLD详解 MySQL 中定义了 ...