zabbix常用的python类api

时间:2023-03-08 16:08:39

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)